@realtimex/folio 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -48,7 +48,7 @@ Request ID: ${m}`),p){let C=`
48
48
  Resources:`;for(const A of p){if(!A||typeof A!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${A}`);C+=`
49
49
  - ${A}`}E+=C}return`${_}
50
50
  ${E}`}class Tt extends Error{constructor({message:e,code:s,cause:i,name:l}){var u;super(e,{cause:i}),this.__isWebAuthnError=!0,this.name=(u=l??(i instanceof Error?i.name:void 0))!==null&&u!==void 0?u:"Unknown Error",this.code=s}}class au extends Tt{constructor(e,s){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s,message:e}),this.name="WebAuthnUnknownError",this.originalError=s}}function QT({error:t,options:e}){var s,i,l;const{publicKey:u}=e;if(!u)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Tt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((s=u.authenticatorSelection)===null||s===void 0?void 0:s.requireResidentKey)===!0)return new Tt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((i=u.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new Tt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((l=u.authenticatorSelection)===null||l===void 0?void 0:l.userVerification)==="required")return new Tt({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new Tt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Tt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return u.pubKeyCredParams.filter(h=>h.type==="public-key").length===0?new Tt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Tt({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const d=window.location.hostname;if(yw(d)){if(u.rp.id!==d)return new Tt({message:`The RP ID "${u.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Tt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(u.user.id.byteLength<1||u.user.id.byteLength>64)return new Tt({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new Tt({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new Tt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function ZT({error:t,options:e}){const{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Tt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Tt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const i=window.location.hostname;if(yw(i)){if(s.rpId!==i)return new Tt({message:`The RP ID "${s.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Tt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Tt({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new Tt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class eE{createNewAbortSignal(){if(this.controller){const s=new Error("Cancelling existing WebAuthn API call for new one");s.name="AbortError",this.controller.abort(s)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const tE=new eE;function nE(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:s,excludeCredentials:i}=t,l=gr(t,["challenge","user","excludeCredentials"]),u=lr(e).buffer,d=Object.assign(Object.assign({},s),{id:lr(s.id).buffer}),h=Object.assign(Object.assign({},l),{challenge:u,user:d});if(i&&i.length>0){h.excludeCredentials=new Array(i.length);for(let m=0;m<i.length;m++){const p=i[m];h.excludeCredentials[m]=Object.assign(Object.assign({},p),{id:lr(p.id).buffer,type:p.type||"public-key",transports:p.transports})}}return h}function sE(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:s}=t,i=gr(t,["challenge","allowCredentials"]),l=lr(e).buffer,u=Object.assign(Object.assign({},i),{challenge:l});if(s&&s.length>0){u.allowCredentials=new Array(s.length);for(let d=0;d<s.length;d++){const h=s[d];u.allowCredentials[d]=Object.assign(Object.assign({},h),{id:lr(h.id).buffer,type:h.type||"public-key",transports:h.transports})}}return u}function aE(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const s=t;return{id:t.id,rawId:t.id,response:{attestationObject:Ka(new Uint8Array(t.response.attestationObject)),clientDataJSON:Ka(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=s.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function iE(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const s=t,i=t.getClientExtensionResults(),l=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Ka(new Uint8Array(l.authenticatorData)),clientDataJSON:Ka(new Uint8Array(l.clientDataJSON)),signature:Ka(new Uint8Array(l.signature)),userHandle:l.userHandle?Ka(new Uint8Array(l.userHandle)):void 0},type:"public-key",clientExtensionResults:i,authenticatorAttachment:(e=s.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function yw(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function s0(){var t,e;return!!(Gt()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function rE(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new au("Browser returned unexpected credential type",e)}:{data:null,error:new au("Empty credential response",e)}}catch(e){return{data:null,error:QT({error:e,options:t})}}}async function oE(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new au("Browser returned unexpected credential type",e)}:{data:null,error:new au("Empty credential response",e)}}catch(e){return{data:null,error:ZT({error:e,options:t})}}}const lE={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},cE={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function iu(...t){const e=l=>l!==null&&typeof l=="object"&&!Array.isArray(l),s=l=>l instanceof ArrayBuffer||ArrayBuffer.isView(l),i={};for(const l of t)if(l)for(const u in l){const d=l[u];if(d!==void 0)if(Array.isArray(d))i[u]=d;else if(s(d))i[u]=d;else if(e(d)){const h=i[u];e(h)?i[u]=iu(h,d):i[u]=iu(d)}else i[u]=d}return i}function uE(t,e){return iu(lE,t,e||{})}function dE(t,e){return iu(cE,t,e||{})}class hE{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:s,friendlyName:i,signal:l},u){var d;try{const{data:h,error:m}=await this.client.mfa.challenge({factorId:e,webauthn:s});if(!h)return{data:null,error:m};const p=l??tE.createNewAbortSignal();if(h.webauthn.type==="create"){const{user:y}=h.webauthn.credential_options.publicKey;if(!y.name){const x=i;if(x)y.name=`${y.id}:${x}`;else{const j=(await this.client.getUser()).data.user,T=((d=j?.user_metadata)===null||d===void 0?void 0:d.name)||j?.email||j?.id||"User";y.name=`${y.id}:${T}`}}y.displayName||(y.displayName=y.name)}switch(h.webauthn.type){case"create":{const y=uE(h.webauthn.credential_options.publicKey,u?.create),{data:x,error:w}=await rE({publicKey:y,signal:p});return x?{data:{factorId:e,challengeId:h.id,webauthn:{type:h.webauthn.type,credential_response:x}},error:null}:{data:null,error:w}}case"request":{const y=dE(h.webauthn.credential_options.publicKey,u?.request),{data:x,error:w}=await oE(Object.assign(Object.assign({},h.webauthn.credential_options),{publicKey:y,signal:p}));return x?{data:{factorId:e,challengeId:h.id,webauthn:{type:h.webauthn.type,credential_response:x}},error:null}:{data:null,error:w}}}}catch(h){return Te(h)?{data:null,error:h}:{data:null,error:new Fa("Unexpected error in challenge",h)}}}async _verify({challengeId:e,factorId:s,webauthn:i}){return this.client.mfa.verify({factorId:s,challengeId:e,webauthn:i})}async _authenticate({factorId:e,webauthn:{rpId:s=typeof window<"u"?window.location.hostname:void 0,rpOrigins:i=typeof window<"u"?[window.location.origin]:void 0,signal:l}={}},u){if(!s)return{data:null,error:new zo("rpId is required for WebAuthn authentication")};try{if(!s0())return{data:null,error:new Fa("Browser does not support WebAuthn",null)};const{data:d,error:h}=await this.challenge({factorId:e,webauthn:{rpId:s,rpOrigins:i},signal:l},{request:u});if(!d)return{data:null,error:h};const{webauthn:m}=d;return this._verify({factorId:e,challengeId:d.challengeId,webauthn:{type:m.type,rpId:s,rpOrigins:i,credential_response:m.credential_response}})}catch(d){return Te(d)?{data:null,error:d}:{data:null,error:new Fa("Unexpected error in authenticate",d)}}}async _register({friendlyName:e,webauthn:{rpId:s=typeof window<"u"?window.location.hostname:void 0,rpOrigins:i=typeof window<"u"?[window.location.origin]:void 0,signal:l}={}},u){if(!s)return{data:null,error:new zo("rpId is required for WebAuthn registration")};try{if(!s0())return{data:null,error:new Fa("Browser does not support WebAuthn",null)};const{data:d,error:h}=await this._enroll({friendlyName:e});if(!d)return await this.client.mfa.listFactors().then(y=>{var x;return(x=y.data)===null||x===void 0?void 0:x.all.find(w=>w.factor_type==="webauthn"&&w.friendly_name===e&&w.status!=="unverified")}).then(y=>y?this.client.mfa.unenroll({factorId:y?.id}):void 0),{data:null,error:h};const{data:m,error:p}=await this._challenge({factorId:d.id,friendlyName:d.friendly_name,webauthn:{rpId:s,rpOrigins:i},signal:l},{create:u});return m?this._verify({factorId:d.id,challengeId:m.challengeId,webauthn:{rpId:s,rpOrigins:i,type:m.webauthn.type,credential_response:m.webauthn.credential_response}}):{data:null,error:p}}catch(d){return Te(d)?{data:null,error:d}:{data:null,error:new Fa("Unexpected error in register",d)}}}}YT();const fE={url:uT,storageKey:dT,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:hT,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function a0(t,e,s){return await s()}const Ki={};class Lo{get jwks(){var e,s;return(s=(e=Ki[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&s!==void 0?s:{keys:[]}}set jwks(e){Ki[this.storageKey]=Object.assign(Object.assign({},Ki[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,s;return(s=(e=Ki[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&s!==void 0?s:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ki[this.storageKey]=Object.assign(Object.assign({},Ki[this.storageKey]),{cachedAt:e})}constructor(e){var s,i,l;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const u=Object.assign(Object.assign({},fE),e);if(this.storageKey=u.storageKey,this.instanceID=(s=Lo.nextInstanceID[this.storageKey])!==null&&s!==void 0?s:0,Lo.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!u.debug,typeof u.debug=="function"&&(this.logger=u.debug),this.instanceID>0&&Gt()){const d=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(d),this.logDebugMessages&&console.trace(d)}if(this.persistSession=u.persistSession,this.autoRefreshToken=u.autoRefreshToken,this.admin=new FT({url:u.url,headers:u.headers,fetch:u.fetch}),this.url=u.url,this.headers=u.headers,this.fetch=mw(u.fetch),this.lock=u.lock||a0,this.detectSessionInUrl=u.detectSessionInUrl,this.flowType=u.flowType,this.hasCustomAuthorizationHeader=u.hasCustomAuthorizationHeader,this.throwOnError=u.throwOnError,this.lockAcquireTimeout=u.lockAcquireTimeout,u.lock?this.lock=u.lock:this.persistSession&&Gt()&&(!((i=globalThis?.navigator)===null||i===void 0)&&i.locks)?this.lock=KT:this.lock=a0,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new hE(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(u.storage?this.storage=u.storage:fw()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=t0(this.memoryStorage)),u.userStorage&&(this.userStorage=u.userStorage)):(this.memoryStorage={},this.storage=t0(this.memoryStorage)),Gt()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(d){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",d)}(l=this.broadcastChannel)===null||l===void 0||l.addEventListener("message",async d=>{this._debug("received broadcast notification from other tab or client",d);try{await this._notifyAllSubscribers(d.data.event,d.data.session,!1)}catch(h){this._debug("#broadcastChannel","error",h)}})}u.skipAutoInitialize||this.initialize().catch(d=>{this._debug("#initialize()","error",d)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${uw}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let s={},i="none";if(Gt()&&(s=TT(window.location.href),this._isImplicitGrantCallback(s)?i="implicit":await this._isPKCECallback(s)&&(i="pkce")),Gt()&&this.detectSessionInUrl&&i!=="none"){const{data:l,error:u}=await this._getSessionFromURL(s,i);if(u){if(this._debug("#_initialize()","error detecting session from URL",u),yT(u)){const m=(e=u.details)===null||e===void 0?void 0:e.code;if(m==="identity_already_exists"||m==="identity_not_found"||m==="single_identity_not_deletable")return{error:u}}return{error:u}}const{session:d,redirectType:h}=l;return this._debug("#_initialize()","detected session in URL",d,"redirect type",h),await this._saveSession(d),setTimeout(async()=>{h==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",d):await this._notifyAllSubscribers("SIGNED_IN",d)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(s){return Te(s)?this._returnResult({error:s}):this._returnResult({error:new Fa("Unexpected error during initialization",s)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var s,i,l;try{const u=await Re(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(i=(s=e?.options)===null||s===void 0?void 0:s.data)!==null&&i!==void 0?i:{},gotrue_meta_security:{captcha_token:(l=e?.options)===null||l===void 0?void 0:l.captchaToken}},xform:$n}),{data:d,error:h}=u;if(h||!d)return this._returnResult({data:{user:null,session:null},error:h});const m=d.session,p=d.user;return d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(u){if(Te(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async signUp(e){var s,i,l;try{let u;if("email"in e){const{email:y,password:x,options:w}=e;let j=null,T=null;this.flowType==="pkce"&&([j,T]=await Hi(this.storage,this.storageKey)),u=await Re(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:w?.emailRedirectTo,body:{email:y,password:x,data:(s=w?.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:w?.captchaToken},code_challenge:j,code_challenge_method:T},xform:$n})}else if("phone"in e){const{phone:y,password:x,options:w}=e;u=await Re(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:y,password:x,data:(i=w?.data)!==null&&i!==void 0?i:{},channel:(l=w?.channel)!==null&&l!==void 0?l:"sms",gotrue_meta_security:{captcha_token:w?.captchaToken}},xform:$n})}else throw new Cc("You must provide either an email or phone number and a password");const{data:d,error:h}=u;if(h||!d)return await Ht(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:h});const m=d.session,p=d.user;return d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(u){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async signInWithPassword(e){try{let s;if("email"in e){const{email:u,password:d,options:h}=e;s=await Re(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:u,password:d,gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:Zx})}else if("phone"in e){const{phone:u,password:d,options:h}=e;s=await Re(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:u,password:d,gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:Zx})}else throw new Cc("You must provide either an email or phone number and a password");const{data:i,error:l}=s;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!i||!i.session||!i.user){const u=new qi;return this._returnResult({data:{user:null,session:null},error:u})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign({user:i.user,session:i.session},i.weak_password?{weakPassword:i.weak_password}:null),error:l})}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOAuth(e){var s,i,l,u;return await this._handleProviderSignIn(e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.redirectTo,scopes:(i=e.options)===null||i===void 0?void 0:i.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:(u=e.options)===null||u===void 0?void 0:u.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:s}=e;switch(s){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${s}"`)}}async signInWithEthereum(e){var s,i,l,u,d,h,m,p,y,x,w;let j,T;if("message"in e)j=e.message,T=e.signature;else{const{chain:S,wallet:_,statement:E,options:C}=e;let A;if(Gt())if(typeof _=="object")A=_;else{const I=window;if("ethereum"in I&&typeof I.ethereum=="object"&&"request"in I.ethereum&&typeof I.ethereum.request=="function")A=I.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof _!="object"||!C?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");A=_}const k=new URL((s=C?.url)!==null&&s!==void 0?s:window.location.href),M=await A.request({method:"eth_requestAccounts"}).then(I=>I).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!M||M.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const P=gw(M[0]);let B=(i=C?.signInWithEthereum)===null||i===void 0?void 0:i.chainId;if(!B){const I=await A.request({method:"eth_chainId"});B=XT(I)}const R={domain:k.host,address:P,statement:E,uri:k.href,version:"1",chainId:B,nonce:(l=C?.signInWithEthereum)===null||l===void 0?void 0:l.nonce,issuedAt:(d=(u=C?.signInWithEthereum)===null||u===void 0?void 0:u.issuedAt)!==null&&d!==void 0?d:new Date,expirationTime:(h=C?.signInWithEthereum)===null||h===void 0?void 0:h.expirationTime,notBefore:(m=C?.signInWithEthereum)===null||m===void 0?void 0:m.notBefore,requestId:(p=C?.signInWithEthereum)===null||p===void 0?void 0:p.requestId,resources:(y=C?.signInWithEthereum)===null||y===void 0?void 0:y.resources};j=JT(R),T=await A.request({method:"personal_sign",params:[WT(j),P]})}try{const{data:S,error:_}=await Re(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:j,signature:T},!((x=e.options)===null||x===void 0)&&x.captchaToken?{gotrue_meta_security:{captcha_token:(w=e.options)===null||w===void 0?void 0:w.captchaToken}}:null),xform:$n});if(_)throw _;if(!S||!S.session||!S.user){const E=new qi;return this._returnResult({data:{user:null,session:null},error:E})}return S.session&&(await this._saveSession(S.session),await this._notifyAllSubscribers("SIGNED_IN",S.session)),this._returnResult({data:Object.assign({},S),error:_})}catch(S){if(Te(S))return this._returnResult({data:{user:null,session:null},error:S});throw S}}async signInWithSolana(e){var s,i,l,u,d,h,m,p,y,x,w,j;let T,S;if("message"in e)T=e.message,S=e.signature;else{const{chain:_,wallet:E,statement:C,options:A}=e;let k;if(Gt())if(typeof E=="object")k=E;else{const P=window;if("solana"in P&&typeof P.solana=="object"&&("signIn"in P.solana&&typeof P.solana.signIn=="function"||"signMessage"in P.solana&&typeof P.solana.signMessage=="function"))k=P.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof E!="object"||!A?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=E}const M=new URL((s=A?.url)!==null&&s!==void 0?s:window.location.href);if("signIn"in k&&k.signIn){const P=await k.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},A?.signInWithSolana),{version:"1",domain:M.host,uri:M.href}),C?{statement:C}:null));let B;if(Array.isArray(P)&&P[0]&&typeof P[0]=="object")B=P[0];else if(P&&typeof P=="object"&&"signedMessage"in P&&"signature"in P)B=P;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in B&&"signature"in B&&(typeof B.signedMessage=="string"||B.signedMessage instanceof Uint8Array)&&B.signature instanceof Uint8Array)T=typeof B.signedMessage=="string"?B.signedMessage:new TextDecoder().decode(B.signedMessage),S=B.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in k)||typeof k.signMessage!="function"||!("publicKey"in k)||typeof k!="object"||!k.publicKey||!("toBase58"in k.publicKey)||typeof k.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");T=[`${M.host} wants you to sign in with your Solana account:`,k.publicKey.toBase58(),...C?["",C,""]:[""],"Version: 1",`URI: ${M.href}`,`Issued At: ${(l=(i=A?.signInWithSolana)===null||i===void 0?void 0:i.issuedAt)!==null&&l!==void 0?l:new Date().toISOString()}`,...!((u=A?.signInWithSolana)===null||u===void 0)&&u.notBefore?[`Not Before: ${A.signInWithSolana.notBefore}`]:[],...!((d=A?.signInWithSolana)===null||d===void 0)&&d.expirationTime?[`Expiration Time: ${A.signInWithSolana.expirationTime}`]:[],...!((h=A?.signInWithSolana)===null||h===void 0)&&h.chainId?[`Chain ID: ${A.signInWithSolana.chainId}`]:[],...!((m=A?.signInWithSolana)===null||m===void 0)&&m.nonce?[`Nonce: ${A.signInWithSolana.nonce}`]:[],...!((p=A?.signInWithSolana)===null||p===void 0)&&p.requestId?[`Request ID: ${A.signInWithSolana.requestId}`]:[],...!((x=(y=A?.signInWithSolana)===null||y===void 0?void 0:y.resources)===null||x===void 0)&&x.length?["Resources",...A.signInWithSolana.resources.map(B=>`- ${B}`)]:[]].join(`
51
- `);const P=await k.signMessage(new TextEncoder().encode(T),"utf8");if(!P||!(P instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");S=P}}try{const{data:_,error:E}=await Re(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Ka(S)},!((w=e.options)===null||w===void 0)&&w.captchaToken?{gotrue_meta_security:{captcha_token:(j=e.options)===null||j===void 0?void 0:j.captchaToken}}:null),xform:$n});if(E)throw E;if(!_||!_.session||!_.user){const C=new qi;return this._returnResult({data:{user:null,session:null},error:C})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:E})}catch(_){if(Te(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const s=await Ua(this.storage,`${this.storageKey}-code-verifier`),[i,l]=(s??"").split("/");try{if(!i&&this.flowType==="pkce")throw new vT;const{data:u,error:d}=await Re(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:i},xform:$n});if(await Ht(this.storage,`${this.storageKey}-code-verifier`),d)throw d;if(!u||!u.session||!u.user){const h=new qi;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:l??null}),error:d})}catch(u){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{const{options:s,provider:i,token:l,access_token:u,nonce:d}=e,h=await Re(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:i,id_token:l,access_token:u,nonce:d,gotrue_meta_security:{captcha_token:s?.captchaToken}},xform:$n}),{data:m,error:p}=h;if(p)return this._returnResult({data:{user:null,session:null},error:p});if(!m||!m.session||!m.user){const y=new qi;return this._returnResult({data:{user:null,session:null},error:y})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:m,error:p})}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOtp(e){var s,i,l,u,d;try{if("email"in e){const{email:h,options:m}=e;let p=null,y=null;this.flowType==="pkce"&&([p,y]=await Hi(this.storage,this.storageKey));const{error:x}=await Re(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:h,data:(s=m?.data)!==null&&s!==void 0?s:{},create_user:(i=m?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:p,code_challenge_method:y},redirectTo:m?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:x})}if("phone"in e){const{phone:h,options:m}=e,{data:p,error:y}=await Re(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:h,data:(l=m?.data)!==null&&l!==void 0?l:{},create_user:(u=m?.shouldCreateUser)!==null&&u!==void 0?u:!0,gotrue_meta_security:{captcha_token:m?.captchaToken},channel:(d=m?.channel)!==null&&d!==void 0?d:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:p?.message_id},error:y})}throw new Cc("You must provide either an email or phone number.")}catch(h){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(h))return this._returnResult({data:{user:null,session:null},error:h});throw h}}async verifyOtp(e){var s,i;try{let l,u;"options"in e&&(l=(s=e.options)===null||s===void 0?void 0:s.redirectTo,u=(i=e.options)===null||i===void 0?void 0:i.captchaToken);const{data:d,error:h}=await Re(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:u}}),redirectTo:l,xform:$n});if(h)throw h;if(!d)throw new Error("An error occurred on token verification.");const m=d.session,p=d.user;return m?.access_token&&(await this._saveSession(m),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(l){if(Te(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async signInWithSSO(e){var s,i,l,u,d;try{let h=null,m=null;this.flowType==="pkce"&&([h,m]=await Hi(this.storage,this.storageKey));const p=await Re(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(i=(s=e.options)===null||s===void 0?void 0:s.redirectTo)!==null&&i!==void 0?i:void 0}),!((l=e?.options)===null||l===void 0)&&l.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:h,code_challenge_method:m}),headers:this.headers,xform:qT});return!((u=p.data)===null||u===void 0)&&u.url&&Gt()&&!(!((d=e.options)===null||d===void 0)&&d.skipBrowserRedirect)&&window.location.assign(p.data.url),this._returnResult(p)}catch(h){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(h))return this._returnResult({data:null,error:h});throw h}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:s},error:i}=e;if(i)throw i;if(!s)throw new xn;const{error:l}=await Re(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return this._returnResult({data:{user:null,session:null},error:l})})}catch(e){if(Te(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const s=`${this.url}/resend`;if("email"in e){const{email:i,type:l,options:u}=e,{error:d}=await Re(this.fetch,"POST",s,{headers:this.headers,body:{email:i,type:l,gotrue_meta_security:{captcha_token:u?.captchaToken}},redirectTo:u?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}else if("phone"in e){const{phone:i,type:l,options:u}=e,{data:d,error:h}=await Re(this.fetch,"POST",s,{headers:this.headers,body:{phone:i,type:l,gotrue_meta_security:{captcha_token:u?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:d?.message_id},error:h})}throw new Cc("You must provide either an email or phone number and a type")}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async s=>s))}async _acquireLock(e,s){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const i=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),l=(async()=>(await i,await s()))();return this.pendingInLock.push((async()=>{try{await l}catch{}})()),l}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const i=s();for(this.pendingInLock.push((async()=>{try{await i}catch{}})()),await i;this.pendingInLock.length;){const l=[...this.pendingInLock];await Promise.all(l),this.pendingInLock.splice(0,l.length)}return await i}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const s=await this.__loadSession();return await e(s)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const s=await Ua(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?e=s:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const i=e.expires_at?e.expires_at*1e3-Date.now()<rf:!1;if(this._debug("#__loadSession()",`session has${i?"":" not"} expired`,"expires_at",e.expires_at),!i){if(this.userStorage){const d=await Ua(this.userStorage,this.storageKey+"-user");d?.user?e.user=d.user:e.user=cf()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const d={value:this.suppressGetSessionWarning};e.user=BT(e.user,d),d.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);return u?this._returnResult({data:{session:null},error:u}):this._returnResult({data:{session:l},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const s=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return s.data.user&&(this.suppressGetSessionWarning=!0),s}async _getUser(e){try{return e?await Re(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ua}):await this._useSession(async s=>{var i,l,u;const{data:d,error:h}=s;if(h)throw h;return!(!((i=d.session)===null||i===void 0)&&i.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new xn}:await Re(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0,xform:ua})})}catch(s){if(Te(s))return of(s)&&(await this._removeSession(),await Ht(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:s});throw s}}async updateUser(e,s={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,s))}async _updateUser(e,s={}){try{return await this._useSession(async i=>{const{data:l,error:u}=i;if(u)throw u;if(!l.session)throw new xn;const d=l.session;let h=null,m=null;this.flowType==="pkce"&&e.email!=null&&([h,m]=await Hi(this.storage,this.storageKey));const{data:p,error:y}=await Re(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:s?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:h,code_challenge_method:m}),jwt:d.access_token,xform:ua});if(y)throw y;return d.user=p.user,await this._saveSession(d),await this._notifyAllSubscribers("USER_UPDATED",d),this._returnResult({data:{user:d.user},error:null})})}catch(i){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(i))return this._returnResult({data:{user:null},error:i});throw i}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new xn;const s=Date.now()/1e3;let i=s,l=!0,u=null;const{payload:d}=Rc(e.access_token);if(d.exp&&(i=d.exp,l=i<=s),l){const{data:h,error:m}=await this._callRefreshToken(e.refresh_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});if(!h)return{data:{user:null,session:null},error:null};u=h}else{const{data:h,error:m}=await this._getUser(e.access_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});u={access_token:e.access_token,refresh_token:e.refresh_token,user:h.user,token_type:"bearer",expires_in:i-s,expires_at:i},await this._saveSession(u),await this._notifyAllSubscribers("SIGNED_IN",u)}return this._returnResult({data:{user:u.user,session:u},error:null})}catch(s){if(Te(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async s=>{var i;if(!e){const{data:d,error:h}=s;if(h)throw h;e=(i=d.session)!==null&&i!==void 0?i:void 0}if(!e?.refresh_token)throw new xn;const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);return u?this._returnResult({data:{user:null,session:null},error:u}):l?this._returnResult({data:{user:l.user,session:l},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async _getSessionFromURL(e,s){try{if(!Gt())throw new Ac("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ac(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(s){case"implicit":if(this.flowType==="pkce")throw new Fx("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ac("Not a valid implicit grant flow url.");break;default:}if(s==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Fx("No code detected.");const{data:C,error:A}=await this._exchangeCodeForSession(e.code);if(A)throw A;const k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:C.session,redirectType:null},error:null}}const{provider_token:i,provider_refresh_token:l,access_token:u,refresh_token:d,expires_in:h,expires_at:m,token_type:p}=e;if(!u||!h||!d||!p)throw new Ac("No session defined in URL");const y=Math.round(Date.now()/1e3),x=parseInt(h);let w=y+x;m&&(w=parseInt(m));const j=w-y;j*1e3<=Qi&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${j}s, should have been closer to ${x}s`);const T=w-x;y-T>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",T,w,y):y-T<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",T,w,y);const{data:S,error:_}=await this._getUser(u);if(_)throw _;const E={provider_token:i,provider_refresh_token:l,access_token:u,expires_in:x,expires_at:w,refresh_token:d,token_type:p,user:S.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:E,redirectType:e.type},error:null})}catch(i){if(Te(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const s=await Ua(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&s)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async s=>{var i;const{data:l,error:u}=s;if(u&&!of(u))return this._returnResult({error:u});const d=(i=l.session)===null||i===void 0?void 0:i.access_token;if(d){const{error:h}=await this.admin.signOut(d,e);if(h&&!(gT(h)&&(h.status===404||h.status===401||h.status===403)||of(h)))return this._returnResult({error:h})}return e!=="others"&&(await this._removeSession(),await Ht(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const s=NT(),i={id:s,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",s),this.stateChangeEmitters.delete(s)}};return this._debug("#onAuthStateChange()","registered callback with id",s),this.stateChangeEmitters.set(s,i),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(s)})))(),{data:{subscription:i}}}async _emitInitialSession(e){return await this._useSession(async s=>{var i,l;try{const{data:{session:u},error:d}=s;if(d)throw d;await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",u)),this._debug("INITIAL_SESSION","callback id",e,"session",u)}catch(u){await((l=this.stateChangeEmitters.get(e))===null||l===void 0?void 0:l.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",u),console.error(u)}})}async resetPasswordForEmail(e,s={}){let i=null,l=null;this.flowType==="pkce"&&([i,l]=await Hi(this.storage,this.storageKey,!0));try{return await Re(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:i,code_challenge_method:l,gotrue_meta_security:{captcha_token:s.captchaToken}},headers:this.headers,redirectTo:s.redirectTo})}catch(u){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(u))return this._returnResult({data:null,error:u});throw u}}async getUserIdentities(){var e;try{const{data:s,error:i}=await this.getUser();if(i)throw i;return this._returnResult({data:{identities:(e=s.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var s;try{const{data:i,error:l}=await this._useSession(async u=>{var d,h,m,p,y;const{data:x,error:w}=u;if(w)throw w;const j=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(d=e.options)===null||d===void 0?void 0:d.redirectTo,scopes:(h=e.options)===null||h===void 0?void 0:h.scopes,queryParams:(m=e.options)===null||m===void 0?void 0:m.queryParams,skipBrowserRedirect:!0});return await Re(this.fetch,"GET",j,{headers:this.headers,jwt:(y=(p=x.session)===null||p===void 0?void 0:p.access_token)!==null&&y!==void 0?y:void 0})});if(l)throw l;return Gt()&&!(!((s=e.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(i?.url),this._returnResult({data:{provider:e.provider,url:i?.url},error:null})}catch(i){if(Te(i))return this._returnResult({data:{provider:e.provider,url:null},error:i});throw i}}async linkIdentityIdToken(e){return await this._useSession(async s=>{var i;try{const{error:l,data:{session:u}}=s;if(l)throw l;const{options:d,provider:h,token:m,access_token:p,nonce:y}=e,x=await Re(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(i=u?.access_token)!==null&&i!==void 0?i:void 0,body:{provider:h,id_token:m,access_token:p,nonce:y,link_identity:!0,gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:$n}),{data:w,error:j}=x;return j?this._returnResult({data:{user:null,session:null},error:j}):!w||!w.session||!w.user?this._returnResult({data:{user:null,session:null},error:new qi}):(w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("USER_UPDATED",w.session)),this._returnResult({data:w,error:j}))}catch(l){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}})}async unlinkIdentity(e){try{return await this._useSession(async s=>{var i,l;const{data:u,error:d}=s;if(d)throw d;return await Re(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(l=(i=u.session)===null||i===void 0?void 0:i.access_token)!==null&&l!==void 0?l:void 0})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _refreshAccessToken(e){const s=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{const i=Date.now();return await CT(async l=>(l>0&&await kT(200*Math.pow(2,l-1)),this._debug(s,"refreshing attempt",l),await Re(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:$n})),(l,u)=>{const d=200*Math.pow(2,l);return u&&lf(u)&&Date.now()+d-i<Qi})}catch(i){if(this._debug(s,"error",i),Te(i))return this._returnResult({data:{session:null,user:null},error:i});throw i}finally{this._debug(s,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,s){const i=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:s.redirectTo,scopes:s.scopes,queryParams:s.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",s,"url",i),Gt()&&!s.skipBrowserRedirect&&window.location.assign(i),{data:{provider:e,url:i},error:null}}async _recoverAndRefresh(){var e,s;const i="#_recoverAndRefresh()";this._debug(i,"begin");try{const l=await Ua(this.storage,this.storageKey);if(l&&this.userStorage){let d=await Ua(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!d&&(d={user:l.user},await Zi(this.userStorage,this.storageKey+"-user",d)),l.user=(e=d?.user)!==null&&e!==void 0?e:cf()}else if(l&&!l.user&&!l.user){const d=await Ua(this.storage,this.storageKey+"-user");d&&d?.user?(l.user=d.user,await Ht(this.storage,this.storageKey+"-user"),await Zi(this.storage,this.storageKey,l)):l.user=cf()}if(this._debug(i,"session from storage",l),!this._isValidSession(l)){this._debug(i,"session is not valid"),l!==null&&await this._removeSession();return}const u=((s=l.expires_at)!==null&&s!==void 0?s:1/0)*1e3-Date.now()<rf;if(this._debug(i,`session has${u?"":" not"} expired with margin of ${rf}s`),u){if(this.autoRefreshToken&&l.refresh_token){const{error:d}=await this._callRefreshToken(l.refresh_token);d&&(console.error(d),lf(d)||(this._debug(i,"refresh failed with a non-retryable error, removing the session",d),await this._removeSession()))}}else if(l.user&&l.user.__isUserNotAvailableProxy===!0)try{const{data:d,error:h}=await this._getUser(l.access_token);!h&&d?.user?(l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("SIGNED_IN",l)):this._debug(i,"could not get user data, skipping SIGNED_IN notification")}catch(d){console.error("Error getting user data:",d),this._debug(i,"error getting user data, skipping SIGNED_IN notification",d)}else await this._notifyAllSubscribers("SIGNED_IN",l)}catch(l){this._debug(i,"error",l),console.error(l);return}finally{this._debug(i,"end")}}async _callRefreshToken(e){var s,i;if(!e)throw new xn;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const l=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(l,"begin");try{this.refreshingDeferred=new Nu;const{data:u,error:d}=await this._refreshAccessToken(e);if(d)throw d;if(!u.session)throw new xn;await this._saveSession(u.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",u.session);const h={data:u.session,error:null};return this.refreshingDeferred.resolve(h),h}catch(u){if(this._debug(l,"error",u),Te(u)){const d={data:null,error:u};return lf(u)||await this._removeSession(),(s=this.refreshingDeferred)===null||s===void 0||s.resolve(d),d}throw(i=this.refreshingDeferred)===null||i===void 0||i.reject(u),u}finally{this.refreshingDeferred=null,this._debug(l,"end")}}async _notifyAllSubscribers(e,s,i=!0){const l=`#_notifyAllSubscribers(${e})`;this._debug(l,"begin",s,`broadcast = ${i}`);try{this.broadcastChannel&&i&&this.broadcastChannel.postMessage({event:e,session:s});const u=[],d=Array.from(this.stateChangeEmitters.values()).map(async h=>{try{await h.callback(e,s)}catch(m){u.push(m)}});if(await Promise.all(d),u.length>0){for(let h=0;h<u.length;h+=1)console.error(u[h]);throw u[0]}}finally{this._debug(l,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ht(this.storage,`${this.storageKey}-code-verifier`);const s=Object.assign({},e),i=s.user&&s.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!i&&s.user&&await Zi(this.userStorage,this.storageKey+"-user",{user:s.user});const l=Object.assign({},s);delete l.user;const u=Jx(l);await Zi(this.storage,this.storageKey,u)}else{const l=Jx(s);await Zi(this.storage,this.storageKey,l)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ht(this.storage,this.storageKey),await Ht(this.storage,this.storageKey+"-code-verifier"),await Ht(this.storage,this.storageKey+"-user"),this.userStorage&&await Ht(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Gt()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(s){console.error("removing visibilitychange callback failed",s)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Qi);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const s=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=s,s&&typeof s=="object"&&typeof s.unref=="function"?s.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(s)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const s=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,s&&clearTimeout(s)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async s=>{const{data:{session:i}}=s;if(!i||!i.refresh_token||!i.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const l=Math.floor((i.expires_at*1e3-e)/Qi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${l} ticks, a tick lasts ${Qi}ms, refresh threshold is ${Yf} ticks`),l<=Yf&&await this._callRefreshToken(i.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof pw)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Gt()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const s=`#_onVisibilityChanged(${e})`;this._debug(s,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(s,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,s,i){const l=[`provider=${encodeURIComponent(s)}`];if(i?.redirectTo&&l.push(`redirect_to=${encodeURIComponent(i.redirectTo)}`),i?.scopes&&l.push(`scopes=${encodeURIComponent(i.scopes)}`),this.flowType==="pkce"){const[u,d]=await Hi(this.storage,this.storageKey),h=new URLSearchParams({code_challenge:`${encodeURIComponent(u)}`,code_challenge_method:`${encodeURIComponent(d)}`});l.push(h.toString())}if(i?.queryParams){const u=new URLSearchParams(i.queryParams);l.push(u.toString())}return i?.skipBrowserRedirect&&l.push(`skip_http_redirect=${i.skipBrowserRedirect}`),`${e}?${l.join("&")}`}async _unenroll(e){try{return await this._useSession(async s=>{var i;const{data:l,error:u}=s;return u?this._returnResult({data:null,error:u}):await Re(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(i=l?.session)===null||i===void 0?void 0:i.access_token})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _enroll(e){try{return await this._useSession(async s=>{var i,l;const{data:u,error:d}=s;if(d)return this._returnResult({data:null,error:d});const h=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:m,error:p}=await Re(this.fetch,"POST",`${this.url}/factors`,{body:h,headers:this.headers,jwt:(i=u?.session)===null||i===void 0?void 0:i.access_token});return p?this._returnResult({data:null,error:p}):(e.factorType==="totp"&&m.type==="totp"&&(!((l=m?.totp)===null||l===void 0)&&l.qr_code)&&(m.totp.qr_code=`data:image/svg+xml;utf-8,${m.totp.qr_code}`),this._returnResult({data:m,error:null}))})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async s=>{var i;const{data:l,error:u}=s;if(u)return this._returnResult({data:null,error:u});const d=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?aE(e.webauthn.credential_response):iE(e.webauthn.credential_response)})}:{code:e.code}),{data:h,error:m}=await Re(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:d,headers:this.headers,jwt:(i=l?.session)===null||i===void 0?void 0:i.access_token});return m?this._returnResult({data:null,error:m}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+h.expires_in},h)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",h),this._returnResult({data:h,error:m}))})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async s=>{var i;const{data:l,error:u}=s;if(u)return this._returnResult({data:null,error:u});const d=await Re(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(i=l?.session)===null||i===void 0?void 0:i.access_token});if(d.error)return d;const{data:h}=d;if(h.type!=="webauthn")return{data:h,error:null};switch(h.webauthn.type){case"create":return{data:Object.assign(Object.assign({},h),{webauthn:Object.assign(Object.assign({},h.webauthn),{credential_options:Object.assign(Object.assign({},h.webauthn.credential_options),{publicKey:nE(h.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},h),{webauthn:Object.assign(Object.assign({},h.webauthn),{credential_options:Object.assign(Object.assign({},h.webauthn.credential_options),{publicKey:sE(h.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}})}async _challengeAndVerify(e){const{data:s,error:i}=await this._challenge({factorId:e.factorId});return i?this._returnResult({data:null,error:i}):await this._verify({factorId:e.factorId,challengeId:s.id,code:e.code})}async _listFactors(){var e;const{data:{user:s},error:i}=await this.getUser();if(i)return{data:null,error:i};const l={all:[],phone:[],totp:[],webauthn:[]};for(const u of(e=s?.factors)!==null&&e!==void 0?e:[])l.all.push(u),u.status==="verified"&&l[u.factor_type].push(u);return{data:l,error:null}}async _getAuthenticatorAssuranceLevel(e){var s,i,l,u;if(e)try{const{payload:j}=Rc(e);let T=null;j.aal&&(T=j.aal);let S=T;const{data:{user:_},error:E}=await this.getUser(e);if(E)return this._returnResult({data:null,error:E});((i=(s=_?.factors)===null||s===void 0?void 0:s.filter(k=>k.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(S="aal2");const A=j.amr||[];return{data:{currentLevel:T,nextLevel:S,currentAuthenticationMethods:A},error:null}}catch(j){if(Te(j))return this._returnResult({data:null,error:j});throw j}const{data:{session:d},error:h}=await this.getSession();if(h)return this._returnResult({data:null,error:h});if(!d)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:m}=Rc(d.access_token);let p=null;m.aal&&(p=m.aal);let y=p;((u=(l=d.user.factors)===null||l===void 0?void 0:l.filter(j=>j.status==="verified"))!==null&&u!==void 0?u:[]).length>0&&(y="aal2");const w=m.amr||[];return{data:{currentLevel:p,nextLevel:y,currentAuthenticationMethods:w},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async s=>{const{data:{session:i},error:l}=s;return l?this._returnResult({data:null,error:l}):i?await Re(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:i.access_token,xform:u=>({data:u,error:null})}):this._returnResult({data:null,error:new xn})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _approveAuthorization(e,s){try{return await this._useSession(async i=>{const{data:{session:l},error:u}=i;if(u)return this._returnResult({data:null,error:u});if(!l)return this._returnResult({data:null,error:new xn});const d=await Re(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"approve"},xform:h=>({data:h,error:null})});return d.data&&d.data.redirect_url&&Gt()&&!s?.skipBrowserRedirect&&window.location.assign(d.data.redirect_url),d})}catch(i){if(Te(i))return this._returnResult({data:null,error:i});throw i}}async _denyAuthorization(e,s){try{return await this._useSession(async i=>{const{data:{session:l},error:u}=i;if(u)return this._returnResult({data:null,error:u});if(!l)return this._returnResult({data:null,error:new xn});const d=await Re(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"deny"},xform:h=>({data:h,error:null})});return d.data&&d.data.redirect_url&&Gt()&&!s?.skipBrowserRedirect&&window.location.assign(d.data.redirect_url),d})}catch(i){if(Te(i))return this._returnResult({data:null,error:i});throw i}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:s},error:i}=e;return i?this._returnResult({data:null,error:i}):s?await Re(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,xform:l=>({data:l,error:null})}):this._returnResult({data:null,error:new xn})})}catch(e){if(Te(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async s=>{const{data:{session:i},error:l}=s;return l?this._returnResult({data:null,error:l}):i?(await Re(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:i.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new xn})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async fetchJwk(e,s={keys:[]}){let i=s.keys.find(h=>h.kid===e);if(i)return i;const l=Date.now();if(i=this.jwks.keys.find(h=>h.kid===e),i&&this.jwks_cached_at+mT>l)return i;const{data:u,error:d}=await Re(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(d)throw d;return!u.keys||u.keys.length===0||(this.jwks=u,this.jwks_cached_at=l,i=u.keys.find(h=>h.kid===e),!i)?null:i}async getClaims(e,s={}){try{let i=e;if(!i){const{data:j,error:T}=await this.getSession();if(T||!j.session)return this._returnResult({data:null,error:T});i=j.session.access_token}const{header:l,payload:u,signature:d,raw:{header:h,payload:m}}=Rc(i);s?.allowExpired||zT(u.exp);const p=!l.alg||l.alg.startsWith("HS")||!l.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(l.kid,s?.keys?{keys:s.keys}:s?.jwks);if(!p){const{error:j}=await this.getUser(i);if(j)throw j;return{data:{claims:u,header:l,signature:d},error:null}}const y=LT(l.alg),x=await crypto.subtle.importKey("jwk",p,y,!0,["verify"]);if(!await crypto.subtle.verify(y,x,d,jT(`${h}.${m}`)))throw new Jf("Invalid JWT signature");return{data:{claims:u,header:l,signature:d},error:null}}catch(i){if(Te(i))return this._returnResult({data:null,error:i});throw i}}}Lo.nextInstanceID={};const mE=Lo,pE="2.97.0";let wo="";typeof Deno<"u"?wo="deno":typeof document<"u"?wo="web":typeof navigator<"u"&&navigator.product==="ReactNative"?wo="react-native":wo="node";const gE={"X-Client-Info":`supabase-js-${wo}/${pE}`},yE={headers:gE},vE={schema:"public"},xE={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bE={};function Uo(t){"@babel/helpers - typeof";return Uo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Uo(t)}function wE(t,e){if(Uo(t)!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var i=s.call(t,e);if(Uo(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function SE(t){var e=wE(t,"string");return Uo(e)=="symbol"?e:e+""}function jE(t,e,s){return(e=SE(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function i0(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),s.push.apply(s,i)}return s}function yt(t){for(var e=1;e<arguments.length;e++){var s=arguments[e]!=null?arguments[e]:{};e%2?i0(Object(s),!0).forEach(function(i){jE(t,i,s[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):i0(Object(s)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(s,i))})}return t}const _E=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),NE=()=>Headers,TE=(t,e,s)=>{const i=_E(s),l=NE();return async(u,d)=>{var h;const m=(h=await e())!==null&&h!==void 0?h:t;let p=new l(d?.headers);return p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${m}`),i(u,yt(yt({},d),{},{headers:p}))}};function EE(t){return t.endsWith("/")?t:t+"/"}function kE(t,e){var s,i;const{db:l,auth:u,realtime:d,global:h}=t,{db:m,auth:p,realtime:y,global:x}=e,w={db:yt(yt({},m),l),auth:yt(yt({},p),u),realtime:yt(yt({},y),d),storage:{},global:yt(yt(yt({},x),h),{},{headers:yt(yt({},(s=x?.headers)!==null&&s!==void 0?s:{}),(i=h?.headers)!==null&&i!==void 0?i:{})}),accessToken:async()=>""};return t.accessToken?w.accessToken=t.accessToken:delete w.accessToken,w}function CE(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(EE(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var AE=class extends mE{constructor(t){super(t)}},RE=class{constructor(t,e,s){var i,l;this.supabaseUrl=t,this.supabaseKey=e;const u=CE(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",u),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",u),this.storageUrl=new URL("storage/v1",u),this.functionsUrl=new URL("functions/v1",u);const d=`sb-${u.hostname.split(".")[0]}-auth-token`,h={db:vE,realtime:bE,auth:yt(yt({},xE),{},{storageKey:d}),global:yE},m=kE(s??{},h);if(this.storageKey=(i=m.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(l=m.global.headers)!==null&&l!==void 0?l:{},m.accessToken)this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(y,x)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(x)} is not possible`)}});else{var p;this.auth=this._initSupabaseAuthClient((p=m.auth)!==null&&p!==void 0?p:{},this.headers,m.global.fetch)}this.fetch=TE(e,this._getAccessToken.bind(this),m.global.fetch),this.realtime=this._initRealtimeClient(yt({headers:this.headers,accessToken:this._getAccessToken.bind(this)},m.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(y=>this.realtime.setAuth(y)).catch(y=>console.warn("Failed to set initial Realtime auth token:",y)),this.rest=new g2(new URL("rest/v1",u).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch,timeout:m.db.timeout,urlLengthLimit:m.db.urlLengthLimit}),this.storage=new cT(this.storageUrl.href,this.headers,this.fetch,s?.storage),m.accessToken||this._listenForAuthEvents()}get functions(){return new l2(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},s={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,s)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,s;if(t.accessToken)return await t.accessToken();const{data:i}=await t.auth.getSession();return(e=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:s,storage:i,userStorage:l,storageKey:u,flowType:d,lock:h,debug:m,throwOnError:p},y,x){const w={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new AE({url:this.authUrl.href,headers:yt(yt({},w),y),storageKey:u,autoRefreshToken:t,persistSession:e,detectSessionInUrl:s,storage:i,userStorage:l,flowType:d,lock:h,debug:m,throwOnError:p,fetch:x,hasCustomAuthorizationHeader:Object.keys(this.headers).some(j=>j.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new M2(this.realtimeUrl.href,yt(yt({},t),{},{params:yt(yt({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,s){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==s?(this.changedAccessToken=s,this.realtime.setAuth(s)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const zm=(t,e,s)=>new RE(t,e,s);function OE(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const s=e.match(/^v(\d+)\./);return s?parseInt(s[1],10)<=18:!1}OE()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function vw(t){var e,s,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var l=t.length;for(e=0;e<l;e++)t[e]&&(s=vw(t[e]))&&(i&&(i+=" "),i+=s)}else for(s in t)t[s]&&(i&&(i+=" "),i+=s);return i}function xw(){for(var t,e,s=0,i="",l=arguments.length;s<l;s++)(t=arguments[s])&&(e=vw(t))&&(i&&(i+=" "),i+=e);return i}const ME=(t,e)=>{const s=new Array(t.length+e.length);for(let i=0;i<t.length;i++)s[i]=t[i];for(let i=0;i<e.length;i++)s[t.length+i]=e[i];return s},DE=(t,e)=>({classGroupId:t,validator:e}),bw=(t=new Map,e=null,s)=>({nextPart:t,validators:e,classGroupId:s}),ru="-",r0=[],PE="arbitrary..",zE=t=>{const e=UE(t),{conflictingClassGroups:s,conflictingClassGroupModifiers:i}=t;return{getClassGroupId:d=>{if(d.startsWith("[")&&d.endsWith("]"))return LE(d);const h=d.split(ru),m=h[0]===""&&h.length>1?1:0;return ww(h,m,e)},getConflictingClassGroupIds:(d,h)=>{if(h){const m=i[d],p=s[d];return m?p?ME(p,m):m:p||r0}return s[d]||r0}}},ww=(t,e,s)=>{if(t.length-e===0)return s.classGroupId;const l=t[e],u=s.nextPart.get(l);if(u){const p=ww(t,e+1,u);if(p)return p}const d=s.validators;if(d===null)return;const h=e===0?t.join(ru):t.slice(e).join(ru),m=d.length;for(let p=0;p<m;p++){const y=d[p];if(y.validator(h))return y.classGroupId}},LE=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),s=e.indexOf(":"),i=e.slice(0,s);return i?PE+i:void 0})(),UE=t=>{const{theme:e,classGroups:s}=t;return BE(s,e)},BE=(t,e)=>{const s=bw();for(const i in t){const l=t[i];Lm(l,s,i,e)}return s},Lm=(t,e,s,i)=>{const l=t.length;for(let u=0;u<l;u++){const d=t[u];VE(d,e,s,i)}},VE=(t,e,s,i)=>{if(typeof t=="string"){IE(t,e,s);return}if(typeof t=="function"){$E(t,e,s,i);return}qE(t,e,s,i)},IE=(t,e,s)=>{const i=t===""?e:Sw(e,t);i.classGroupId=s},$E=(t,e,s,i)=>{if(HE(t)){Lm(t(i),e,s,i);return}e.validators===null&&(e.validators=[]),e.validators.push(DE(s,t))},qE=(t,e,s,i)=>{const l=Object.entries(t),u=l.length;for(let d=0;d<u;d++){const[h,m]=l[d];Lm(m,Sw(e,h),s,i)}},Sw=(t,e)=>{let s=t;const i=e.split(ru),l=i.length;for(let u=0;u<l;u++){const d=i[u];let h=s.nextPart.get(d);h||(h=bw(),s.nextPart.set(d,h)),s=h}return s},HE=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,GE=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,s=Object.create(null),i=Object.create(null);const l=(u,d)=>{s[u]=d,e++,e>t&&(e=0,i=s,s=Object.create(null))};return{get(u){let d=s[u];if(d!==void 0)return d;if((d=i[u])!==void 0)return l(u,d),d},set(u,d){u in s?s[u]=d:l(u,d)}}},Qf="!",o0=":",FE=[],l0=(t,e,s,i,l)=>({modifiers:t,hasImportantModifier:e,baseClassName:s,maybePostfixModifierPosition:i,isExternal:l}),KE=t=>{const{prefix:e,experimentalParseClassName:s}=t;let i=l=>{const u=[];let d=0,h=0,m=0,p;const y=l.length;for(let S=0;S<y;S++){const _=l[S];if(d===0&&h===0){if(_===o0){u.push(l.slice(m,S)),m=S+1;continue}if(_==="/"){p=S;continue}}_==="["?d++:_==="]"?d--:_==="("?h++:_===")"&&h--}const x=u.length===0?l:l.slice(m);let w=x,j=!1;x.endsWith(Qf)?(w=x.slice(0,-1),j=!0):x.startsWith(Qf)&&(w=x.slice(1),j=!0);const T=p&&p>m?p-m:void 0;return l0(u,j,w,T)};if(e){const l=e+o0,u=i;i=d=>d.startsWith(l)?u(d.slice(l.length)):l0(FE,!1,d,void 0,!0)}if(s){const l=i;i=u=>s({className:u,parseClassName:l})}return i},YE=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((s,i)=>{e.set(s,1e6+i)}),s=>{const i=[];let l=[];for(let u=0;u<s.length;u++){const d=s[u],h=d[0]==="[",m=e.has(d);h||m?(l.length>0&&(l.sort(),i.push(...l),l=[]),i.push(d)):l.push(d)}return l.length>0&&(l.sort(),i.push(...l)),i}},XE=t=>({cache:GE(t.cacheSize),parseClassName:KE(t),sortModifiers:YE(t),...zE(t)}),WE=/\s+/,JE=(t,e)=>{const{parseClassName:s,getClassGroupId:i,getConflictingClassGroupIds:l,sortModifiers:u}=e,d=[],h=t.trim().split(WE);let m="";for(let p=h.length-1;p>=0;p-=1){const y=h[p],{isExternal:x,modifiers:w,hasImportantModifier:j,baseClassName:T,maybePostfixModifierPosition:S}=s(y);if(x){m=y+(m.length>0?" "+m:m);continue}let _=!!S,E=i(_?T.substring(0,S):T);if(!E){if(!_){m=y+(m.length>0?" "+m:m);continue}if(E=i(T),!E){m=y+(m.length>0?" "+m:m);continue}_=!1}const C=w.length===0?"":w.length===1?w[0]:u(w).join(":"),A=j?C+Qf:C,k=A+E;if(d.indexOf(k)>-1)continue;d.push(k);const M=l(E,_);for(let P=0;P<M.length;++P){const B=M[P];d.push(A+B)}m=y+(m.length>0?" "+m:m)}return m},QE=(...t)=>{let e=0,s,i,l="";for(;e<t.length;)(s=t[e++])&&(i=jw(s))&&(l&&(l+=" "),l+=i);return l},jw=t=>{if(typeof t=="string")return t;let e,s="";for(let i=0;i<t.length;i++)t[i]&&(e=jw(t[i]))&&(s&&(s+=" "),s+=e);return s},ZE=(t,...e)=>{let s,i,l,u;const d=m=>{const p=e.reduce((y,x)=>x(y),t());return s=XE(p),i=s.cache.get,l=s.cache.set,u=h,h(m)},h=m=>{const p=i(m);if(p)return p;const y=JE(m,s);return l(m,y),y};return u=d,(...m)=>u(QE(...m))},ek=[],At=t=>{const e=s=>s[t]||ek;return e.isThemeGetter=!0,e},_w=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Nw=/^\((?:(\w[\w-]*):)?(.+)\)$/i,tk=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,nk=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,sk=/\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$/,ak=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ik=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,rk=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,aa=t=>tk.test(t),Ue=t=>!!t&&!Number.isNaN(Number(t)),ia=t=>!!t&&Number.isInteger(Number(t)),df=t=>t.endsWith("%")&&Ue(t.slice(0,-1)),Es=t=>nk.test(t),Tw=()=>!0,ok=t=>sk.test(t)&&!ak.test(t),Um=()=>!1,lk=t=>ik.test(t),ck=t=>rk.test(t),uk=t=>!be(t)&&!Se(t),dk=t=>ga(t,Cw,Um),be=t=>_w.test(t),Ba=t=>ga(t,Aw,ok),c0=t=>ga(t,xk,Ue),hk=t=>ga(t,Ow,Tw),fk=t=>ga(t,Rw,Um),u0=t=>ga(t,Ew,Um),mk=t=>ga(t,kw,ck),Oc=t=>ga(t,Mw,lk),Se=t=>Nw.test(t),xo=t=>ni(t,Aw),pk=t=>ni(t,Rw),d0=t=>ni(t,Ew),gk=t=>ni(t,Cw),yk=t=>ni(t,kw),Mc=t=>ni(t,Mw,!0),vk=t=>ni(t,Ow,!0),ga=(t,e,s)=>{const i=_w.exec(t);return i?i[1]?e(i[1]):s(i[2]):!1},ni=(t,e,s=!1)=>{const i=Nw.exec(t);return i?i[1]?e(i[1]):s:!1},Ew=t=>t==="position"||t==="percentage",kw=t=>t==="image"||t==="url",Cw=t=>t==="length"||t==="size"||t==="bg-size",Aw=t=>t==="length",xk=t=>t==="number",Rw=t=>t==="family-name",Ow=t=>t==="number"||t==="weight",Mw=t=>t==="shadow",bk=()=>{const t=At("color"),e=At("font"),s=At("text"),i=At("font-weight"),l=At("tracking"),u=At("leading"),d=At("breakpoint"),h=At("container"),m=At("spacing"),p=At("radius"),y=At("shadow"),x=At("inset-shadow"),w=At("text-shadow"),j=At("drop-shadow"),T=At("blur"),S=At("perspective"),_=At("aspect"),E=At("ease"),C=At("animate"),A=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],M=()=>[...k(),Se,be],P=()=>["auto","hidden","clip","visible","scroll"],B=()=>["auto","contain","none"],R=()=>[Se,be,m],I=()=>[aa,"full","auto",...R()],te=()=>[ia,"none","subgrid",Se,be],ie=()=>["auto",{span:["full",ia,Se,be]},ia,Se,be],fe=()=>[ia,"auto",Se,be],Ne=()=>["auto","min","max","fr",Se,be],ye=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],se=()=>["start","end","center","stretch","center-safe","end-safe"],V=()=>["auto",...R()],F=()=>[aa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...R()],J=()=>[aa,"screen","full","dvw","lvw","svw","min","max","fit",...R()],ge=()=>[aa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...R()],ne=()=>[t,Se,be],D=()=>[...k(),d0,u0,{position:[Se,be]}],L=()=>["no-repeat",{repeat:["","x","y","space","round"]}],W=()=>["auto","cover","contain",gk,dk,{size:[Se,be]}],ee=()=>[df,xo,Ba],le=()=>["","none","full",p,Se,be],de=()=>["",Ue,xo,Ba],q=()=>["solid","dashed","dotted","double"],pe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],oe=()=>[Ue,df,d0,u0],ze=()=>["","none",T,Se,be],Be=()=>["none",Ue,Se,be],kt=()=>["none",Ue,Se,be],et=()=>[Ue,Se,be],ce=()=>[aa,"full",...R()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Es],breakpoint:[Es],color:[Tw],container:[Es],"drop-shadow":[Es],ease:["in","out","in-out"],font:[uk],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Es],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Es],shadow:[Es],spacing:["px",Ue],text:[Es],"text-shadow":[Es],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",aa,be,Se,_]}],container:["container"],columns:[{columns:[Ue,be,Se,h]}],"break-after":[{"break-after":A()}],"break-before":[{"break-before":A()}],"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"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:M()}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:I()}],"inset-x":[{"inset-x":I()}],"inset-y":[{"inset-y":I()}],start:[{"inset-s":I(),start:I()}],end:[{"inset-e":I(),end:I()}],"inset-bs":[{"inset-bs":I()}],"inset-be":[{"inset-be":I()}],top:[{top:I()}],right:[{right:I()}],bottom:[{bottom:I()}],left:[{left:I()}],visibility:["visible","invisible","collapse"],z:[{z:[ia,"auto",Se,be]}],basis:[{basis:[aa,"full","auto",h,...R()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ue,aa,"auto","initial","none",be]}],grow:[{grow:["",Ue,Se,be]}],shrink:[{shrink:["",Ue,Se,be]}],order:[{order:[ia,"first","last","none",Se,be]}],"grid-cols":[{"grid-cols":te()}],"col-start-end":[{col:ie()}],"col-start":[{"col-start":fe()}],"col-end":[{"col-end":fe()}],"grid-rows":[{"grid-rows":te()}],"row-start-end":[{row:ie()}],"row-start":[{"row-start":fe()}],"row-end":[{"row-end":fe()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":Ne()}],"auto-rows":[{"auto-rows":Ne()}],gap:[{gap:R()}],"gap-x":[{"gap-x":R()}],"gap-y":[{"gap-y":R()}],"justify-content":[{justify:[...ye(),"normal"]}],"justify-items":[{"justify-items":[...se(),"normal"]}],"justify-self":[{"justify-self":["auto",...se()]}],"align-content":[{content:["normal",...ye()]}],"align-items":[{items:[...se(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...se(),{baseline:["","last"]}]}],"place-content":[{"place-content":ye()}],"place-items":[{"place-items":[...se(),"baseline"]}],"place-self":[{"place-self":["auto",...se()]}],p:[{p:R()}],px:[{px:R()}],py:[{py:R()}],ps:[{ps:R()}],pe:[{pe:R()}],pbs:[{pbs:R()}],pbe:[{pbe:R()}],pt:[{pt:R()}],pr:[{pr:R()}],pb:[{pb:R()}],pl:[{pl:R()}],m:[{m:V()}],mx:[{mx:V()}],my:[{my:V()}],ms:[{ms:V()}],me:[{me:V()}],mbs:[{mbs:V()}],mbe:[{mbe:V()}],mt:[{mt:V()}],mr:[{mr:V()}],mb:[{mb:V()}],ml:[{ml:V()}],"space-x":[{"space-x":R()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":R()}],"space-y-reverse":["space-y-reverse"],size:[{size:F()}],"inline-size":[{inline:["auto",...J()]}],"min-inline-size":[{"min-inline":["auto",...J()]}],"max-inline-size":[{"max-inline":["none",...J()]}],"block-size":[{block:["auto",...ge()]}],"min-block-size":[{"min-block":["auto",...ge()]}],"max-block-size":[{"max-block":["none",...ge()]}],w:[{w:[h,"screen",...F()]}],"min-w":[{"min-w":[h,"screen","none",...F()]}],"max-w":[{"max-w":[h,"screen","none","prose",{screen:[d]},...F()]}],h:[{h:["screen","lh",...F()]}],"min-h":[{"min-h":["screen","lh","none",...F()]}],"max-h":[{"max-h":["screen","lh",...F()]}],"font-size":[{text:["base",s,xo,Ba]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,vk,hk]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",df,be]}],"font-family":[{font:[pk,fk,e]}],"font-features":[{"font-features":[be]}],"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:[l,Se,be]}],"line-clamp":[{"line-clamp":[Ue,"none",Se,c0]}],leading:[{leading:[u,...R()]}],"list-image":[{"list-image":["none",Se,be]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Se,be]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:ne()}],"text-color":[{text:ne()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...q(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ue,"from-font","auto",Se,Ba]}],"text-decoration-color":[{decoration:ne()}],"underline-offset":[{"underline-offset":[Ue,"auto",Se,be]}],"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",Se,be]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Se,be]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:D()}],"bg-repeat":[{bg:L()}],"bg-size":[{bg:W()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ia,Se,be],radial:["",Se,be],conic:[ia,Se,be]},yk,mk]}],"bg-color":[{bg:ne()}],"gradient-from-pos":[{from:ee()}],"gradient-via-pos":[{via:ee()}],"gradient-to-pos":[{to:ee()}],"gradient-from":[{from:ne()}],"gradient-via":[{via:ne()}],"gradient-to":[{to:ne()}],rounded:[{rounded:le()}],"rounded-s":[{"rounded-s":le()}],"rounded-e":[{"rounded-e":le()}],"rounded-t":[{"rounded-t":le()}],"rounded-r":[{"rounded-r":le()}],"rounded-b":[{"rounded-b":le()}],"rounded-l":[{"rounded-l":le()}],"rounded-ss":[{"rounded-ss":le()}],"rounded-se":[{"rounded-se":le()}],"rounded-ee":[{"rounded-ee":le()}],"rounded-es":[{"rounded-es":le()}],"rounded-tl":[{"rounded-tl":le()}],"rounded-tr":[{"rounded-tr":le()}],"rounded-br":[{"rounded-br":le()}],"rounded-bl":[{"rounded-bl":le()}],"border-w":[{border:de()}],"border-w-x":[{"border-x":de()}],"border-w-y":[{"border-y":de()}],"border-w-s":[{"border-s":de()}],"border-w-e":[{"border-e":de()}],"border-w-bs":[{"border-bs":de()}],"border-w-be":[{"border-be":de()}],"border-w-t":[{"border-t":de()}],"border-w-r":[{"border-r":de()}],"border-w-b":[{"border-b":de()}],"border-w-l":[{"border-l":de()}],"divide-x":[{"divide-x":de()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":de()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...q(),"hidden","none"]}],"divide-style":[{divide:[...q(),"hidden","none"]}],"border-color":[{border:ne()}],"border-color-x":[{"border-x":ne()}],"border-color-y":[{"border-y":ne()}],"border-color-s":[{"border-s":ne()}],"border-color-e":[{"border-e":ne()}],"border-color-bs":[{"border-bs":ne()}],"border-color-be":[{"border-be":ne()}],"border-color-t":[{"border-t":ne()}],"border-color-r":[{"border-r":ne()}],"border-color-b":[{"border-b":ne()}],"border-color-l":[{"border-l":ne()}],"divide-color":[{divide:ne()}],"outline-style":[{outline:[...q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ue,Se,be]}],"outline-w":[{outline:["",Ue,xo,Ba]}],"outline-color":[{outline:ne()}],shadow:[{shadow:["","none",y,Mc,Oc]}],"shadow-color":[{shadow:ne()}],"inset-shadow":[{"inset-shadow":["none",x,Mc,Oc]}],"inset-shadow-color":[{"inset-shadow":ne()}],"ring-w":[{ring:de()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:ne()}],"ring-offset-w":[{"ring-offset":[Ue,Ba]}],"ring-offset-color":[{"ring-offset":ne()}],"inset-ring-w":[{"inset-ring":de()}],"inset-ring-color":[{"inset-ring":ne()}],"text-shadow":[{"text-shadow":["none",w,Mc,Oc]}],"text-shadow-color":[{"text-shadow":ne()}],opacity:[{opacity:[Ue,Se,be]}],"mix-blend":[{"mix-blend":[...pe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":pe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ue]}],"mask-image-linear-from-pos":[{"mask-linear-from":oe()}],"mask-image-linear-to-pos":[{"mask-linear-to":oe()}],"mask-image-linear-from-color":[{"mask-linear-from":ne()}],"mask-image-linear-to-color":[{"mask-linear-to":ne()}],"mask-image-t-from-pos":[{"mask-t-from":oe()}],"mask-image-t-to-pos":[{"mask-t-to":oe()}],"mask-image-t-from-color":[{"mask-t-from":ne()}],"mask-image-t-to-color":[{"mask-t-to":ne()}],"mask-image-r-from-pos":[{"mask-r-from":oe()}],"mask-image-r-to-pos":[{"mask-r-to":oe()}],"mask-image-r-from-color":[{"mask-r-from":ne()}],"mask-image-r-to-color":[{"mask-r-to":ne()}],"mask-image-b-from-pos":[{"mask-b-from":oe()}],"mask-image-b-to-pos":[{"mask-b-to":oe()}],"mask-image-b-from-color":[{"mask-b-from":ne()}],"mask-image-b-to-color":[{"mask-b-to":ne()}],"mask-image-l-from-pos":[{"mask-l-from":oe()}],"mask-image-l-to-pos":[{"mask-l-to":oe()}],"mask-image-l-from-color":[{"mask-l-from":ne()}],"mask-image-l-to-color":[{"mask-l-to":ne()}],"mask-image-x-from-pos":[{"mask-x-from":oe()}],"mask-image-x-to-pos":[{"mask-x-to":oe()}],"mask-image-x-from-color":[{"mask-x-from":ne()}],"mask-image-x-to-color":[{"mask-x-to":ne()}],"mask-image-y-from-pos":[{"mask-y-from":oe()}],"mask-image-y-to-pos":[{"mask-y-to":oe()}],"mask-image-y-from-color":[{"mask-y-from":ne()}],"mask-image-y-to-color":[{"mask-y-to":ne()}],"mask-image-radial":[{"mask-radial":[Se,be]}],"mask-image-radial-from-pos":[{"mask-radial-from":oe()}],"mask-image-radial-to-pos":[{"mask-radial-to":oe()}],"mask-image-radial-from-color":[{"mask-radial-from":ne()}],"mask-image-radial-to-color":[{"mask-radial-to":ne()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":oe()}],"mask-image-conic-to-pos":[{"mask-conic-to":oe()}],"mask-image-conic-from-color":[{"mask-conic-from":ne()}],"mask-image-conic-to-color":[{"mask-conic-to":ne()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:D()}],"mask-repeat":[{mask:L()}],"mask-size":[{mask:W()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Se,be]}],filter:[{filter:["","none",Se,be]}],blur:[{blur:ze()}],brightness:[{brightness:[Ue,Se,be]}],contrast:[{contrast:[Ue,Se,be]}],"drop-shadow":[{"drop-shadow":["","none",j,Mc,Oc]}],"drop-shadow-color":[{"drop-shadow":ne()}],grayscale:[{grayscale:["",Ue,Se,be]}],"hue-rotate":[{"hue-rotate":[Ue,Se,be]}],invert:[{invert:["",Ue,Se,be]}],saturate:[{saturate:[Ue,Se,be]}],sepia:[{sepia:["",Ue,Se,be]}],"backdrop-filter":[{"backdrop-filter":["","none",Se,be]}],"backdrop-blur":[{"backdrop-blur":ze()}],"backdrop-brightness":[{"backdrop-brightness":[Ue,Se,be]}],"backdrop-contrast":[{"backdrop-contrast":[Ue,Se,be]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ue,Se,be]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ue,Se,be]}],"backdrop-invert":[{"backdrop-invert":["",Ue,Se,be]}],"backdrop-opacity":[{"backdrop-opacity":[Ue,Se,be]}],"backdrop-saturate":[{"backdrop-saturate":[Ue,Se,be]}],"backdrop-sepia":[{"backdrop-sepia":["",Ue,Se,be]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":R()}],"border-spacing-x":[{"border-spacing-x":R()}],"border-spacing-y":[{"border-spacing-y":R()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Se,be]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ue,"initial",Se,be]}],ease:[{ease:["linear","initial",E,Se,be]}],delay:[{delay:[Ue,Se,be]}],animate:[{animate:["none",C,Se,be]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Se,be]}],"perspective-origin":[{"perspective-origin":M()}],rotate:[{rotate:Be()}],"rotate-x":[{"rotate-x":Be()}],"rotate-y":[{"rotate-y":Be()}],"rotate-z":[{"rotate-z":Be()}],scale:[{scale:kt()}],"scale-x":[{"scale-x":kt()}],"scale-y":[{"scale-y":kt()}],"scale-z":[{"scale-z":kt()}],"scale-3d":["scale-3d"],skew:[{skew:et()}],"skew-x":[{"skew-x":et()}],"skew-y":[{"skew-y":et()}],transform:[{transform:[Se,be,"","none","gpu","cpu"]}],"transform-origin":[{origin:M()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ce()}],"translate-x":[{"translate-x":ce()}],"translate-y":[{"translate-y":ce()}],"translate-z":[{"translate-z":ce()}],"translate-none":["translate-none"],accent:[{accent:ne()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:ne()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],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",Se,be]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],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-mbs":[{"scroll-mbs":R()}],"scroll-mbe":[{"scroll-mbe":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-pbs":[{"scroll-pbs":R()}],"scroll-pbe":[{"scroll-pbe":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",Se,be]}],fill:[{fill:["none",...ne()]}],"stroke-w":[{stroke:[Ue,xo,Ba,c0]}],stroke:[{stroke:["none",...ne()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","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","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","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-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","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-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","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"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","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-pbs","scroll-pbe","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"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},wk=ZE(bk);function ve(...t){return wk(xw(t))}const ht=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("rounded-xl border bg-card text-card-foreground shadow",t),...e}));ht.displayName="Card";const zt=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("flex flex-col space-y-1.5 p-6",t),...e}));zt.displayName="CardHeader";const Lt=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("font-semibold leading-none tracking-tight",t),...e}));Lt.displayName="CardTitle";const wn=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("text-sm text-muted-foreground",t),...e}));wn.displayName="CardDescription";const xt=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("p-6 pt-0",t),...e}));xt.displayName="CardContent";const Tu=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("flex items-center p-6 pt-0",t),...e}));Tu.displayName="CardFooter";function ou({className:t}){return o.jsx("img",{src:"/folio-logo.svg",alt:"Folio Logo",className:ve("w-full h-full object-contain",t)})}const Dw=(...t)=>t.filter((e,s,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===s).join(" ").trim();const Sk=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const jk=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,s,i)=>i?i.toUpperCase():s.toLowerCase());const h0=t=>{const e=jk(t);return e.charAt(0).toUpperCase()+e.slice(1)};var _k={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Nk=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Tk=v.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:s=2,absoluteStrokeWidth:i,className:l="",children:u,iconNode:d,...h},m)=>v.createElement("svg",{ref:m,..._k,width:e,height:e,stroke:t,strokeWidth:i?Number(s)*24/Number(e):s,className:Dw("lucide",l),...!u&&!Nk(h)&&{"aria-hidden":"true"},...h},[...d.map(([p,y])=>v.createElement(p,y)),...Array.isArray(u)?u:[u]]));const me=(t,e)=>{const s=v.forwardRef(({className:i,...l},u)=>v.createElement(Tk,{ref:u,iconNode:e,className:Dw(`lucide-${Sk(h0(t))}`,`lucide-${t}`,i),...l}));return s.displayName=h0(t),s};const Ek=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],dr=me("activity",Ek);const kk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ck=me("arrow-right",kk);const Ak=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Rk=me("book-open",Ak);const Ok=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Zf=me("bot",Ok);const Mk=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],Pw=me("brain",Mk);const Dk=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],Pk=me("building-2",Dk);const zk=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],zw=me("calendar",zk);const Lk=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],Uk=me("camera",Lk);const Bk=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],as=me("check",Bk);const Vk=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Bo=me("chevron-down",Vk);const Ik=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Jo=me("chevron-left",Ik);const $k=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],hr=me("chevron-right",$k);const qk=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],lu=me("chevron-up",qk);const Hk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Sn=me("circle-alert",Hk);const Gk=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Fk=me("circle-check-big",Gk);const Kk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],os=me("circle-check",Kk);const Yk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],Lw=me("circle-x",Yk);const Xk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Qo=me("clock",Xk);const Wk=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],f0=me("cloud",Wk);const Jk=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Qk=me("copy",Jk);const Zk=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],Bm=me("cpu",Zk);const eC=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Eu=me("database",eC);const tC=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Uw=me("external-link",tC);const nC=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],sC=me("eye-off",nC);const aC=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],iC=me("eye",aC);const rC=[["path",{d:"M4 12V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2",key:"jrl274"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 16h2v6",key:"1bxocy"}],["path",{d:"M10 22h4",key:"ceow96"}],["rect",{x:"2",y:"16",width:"4",height:"6",rx:"2",key:"r45zd0"}]],oC=me("file-digit",rC);const lC=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Vm=me("file-text",lC);const cC=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Bw=me("funnel",cC);const uC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],dC=me("globe",uC);const hC=[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]],fC=me("hard-drive",hC);const mC=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],pC=me("history",mC);const gC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Im=me("info",gC);const yC=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],Zo=me("key",yC);const vC=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],xC=me("layers",vC);const bC=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],m0=me("layout-dashboard",bC);const wC=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=me("loader-circle",wC);const SC=[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]],Vw=me("log-in",SC);const jC=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],Iw=me("log-out",jC);const _C=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],Vo=me("mail",_C);const NC=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],cu=me("message-square",NC);const TC=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],$w=me("minimize-2",TC);const EC=[["path",{d:"M5 12h14",key:"1ays0h"}]],em=me("minus",EC);const kC=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],CC=me("moon",kC);const AC=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],RC=me("package",AC);const OC=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],qw=me("play",OC);const MC=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ja=me("plus",MC);const DC=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],PC=me("refresh-ccw",DC);const zC=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],ma=me("refresh-cw",zC);const LC=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],UC=me("rocket",LC);const BC=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],VC=me("save",BC);const IC=[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]],Hw=me("scroll-text",IC);const $C=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],qC=me("search",$C);const HC=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],GC=me("send",HC);const FC=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],KC=me("server",FC);const YC=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],$m=me("settings-2",YC);const XC=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],WC=me("settings",XC);const JC=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],p0=me("share-2",JC);const QC=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],uu=me("shield-alert",QC);const ZC=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],ya=me("shield-check",ZC);const eA=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Cs=me("sparkles",eA);const tA=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],nA=me("sun",tA);const sA=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],du=me("tag",sA);const aA=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Io=me("terminal",aA);const iA=[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]],rA=me("test-tube",iA);const oA=[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],lA=me("toggle-left",oA);const cA=[["circle",{cx:"15",cy:"12",r:"3",key:"1afu0r"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],uA=me("toggle-right",cA);const dA=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],el=me("trash-2",dA);const hA=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Gw=me("triangle-alert",hA);const fA=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],tm=me("upload",fA);const mA=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],pA=me("user-plus",mA);const gA=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],ku=me("user",gA);const yA=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],nm=me("volume-2",yA);const vA=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],Fw=me("volume-x",vA);const xA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],zn=me("x",xA);const bA=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],hu=me("zap",bA),Cu="folio_supabase_config";function g0(t){if(!t||typeof t!="object")return!1;const e=t;return typeof e.url=="string"&&typeof e.anonKey=="string"&&e.url.startsWith("http")&&e.anonKey.length>20&&!e.url.includes("placeholder.supabase.co")}function $o(){try{const e=localStorage.getItem(Cu);if(e){const s=JSON.parse(e);if(g0(s))return s}}catch{}const t={url:void 0,anonKey:void 0};return g0(t)?t:null}function hf(t){localStorage.setItem(Cu,JSON.stringify(t))}function wA(){localStorage.removeItem(Cu)}async function SA(t,e){if(!t.startsWith("http://")&&!t.startsWith("https://"))return{valid:!1,error:"Invalid URL format"};const s=e.startsWith("eyJ"),i=e.startsWith("sb_publishable_");if(!s&&!i)return{valid:!1,error:"Invalid anon key format"};if(i)return{valid:!0};const l=new AbortController,u=setTimeout(()=>l.abort("Validation timeout"),12e3);try{const d=await fetch(`${t}/rest/v1/`,{method:"GET",headers:{apikey:e,Authorization:`Bearer ${e}`},signal:l.signal});return d.ok?(clearTimeout(u),{valid:!0}):(clearTimeout(u),{valid:!1,error:`Connection failed (${d.status})`})}catch(d){return clearTimeout(u),d instanceof DOMException&&d.name==="AbortError"?{valid:!1,error:"Connection validation timed out (12s). Check project URL/key and network."}:{valid:!1,error:d instanceof Error?d.message:"Connection failed"}}}function jA(){return localStorage.getItem(Cu)?"ui":"none"}let Dc=null;function un(){const t=$o();return t?(Dc||(Dc=zm(t.url,t.anonKey,{auth:{autoRefreshToken:!0,persistSession:!0}})),Dc):(Dc=null,null)}function ff(){const t=$o(),e=t?`${t.url}/functions/v1`:"",s=t?.anonKey??"",u=window.location.port==="5173"?void 0||"http://localhost:3006":window.location.origin;return{edgeFunctionsUrl:e,expressApiUrl:u,anonKey:s}}class _A{edgeFunctionsUrl;expressApiUrl;anonKey;constructor(){const e=ff();this.edgeFunctionsUrl=e.edgeFunctionsUrl,this.expressApiUrl=e.expressApiUrl,this.anonKey=e.anonKey}async request(e,s,i={}){const{auth:l=!1,token:u,...d}=i,h={"Content-Type":"application/json",...d.headers||{}};l&&u&&(h.Authorization=`Bearer ${u}`);try{const m=await fetch(`${e}${s}`,{...d,headers:h}),p=await m.json().catch(()=>({}));return m.ok?{data:p}:{error:{code:p?.error?.code||"API_ERROR",message:p?.error?.message||p?.error||`Request failed (${m.status})`}}}catch(m){return{error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}edgeRequest(e,s={}){const i={...s.headers||{},apikey:this.anonKey};return this.request(this.edgeFunctionsUrl,e,{...s,headers:i})}expressRequest(e,s={}){const i=ff(),l={...s.headers||{},"X-Supabase-Url":i.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":i.anonKey};return this.request(this.expressApiUrl,e,{...s,headers:l})}get(e,s={}){return this.expressRequest(e,{method:"GET",...s,auth:!0})}post(e,s,i={}){return this.expressRequest(e,{method:"POST",body:s?JSON.stringify(s):void 0,...i,auth:!0})}getChatSessions(e){return this.expressRequest("/api/chat/sessions",{method:"GET",auth:!!e,token:e})}getDashboardStats(e){return this.expressRequest("/api/stats",{method:"GET",auth:!!e,token:e})}createChatSession(e){return this.expressRequest("/api/chat/sessions",{method:"POST",auth:!!e,token:e})}getChatMessages(e,s){return this.expressRequest(`/api/chat/sessions/${e}/messages`,{method:"GET",auth:!!s,token:s})}sendChatMessage(e,s){return this.expressRequest("/api/chat/message",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}getHealth(){return this.expressRequest("/api/health",{method:"GET"})}testSupabase(e,s){return this.expressRequest("/api/setup/test-supabase",{method:"POST",body:JSON.stringify({url:e,anonKey:s})})}dispatchProcessingJob(e,s){return this.expressRequest("/api/processing/dispatch",{method:"POST",auth:!!s,token:s,body:JSON.stringify({source_type:"manual",payload:e})})}getSettings(e){return this.expressRequest("/api/settings",{method:"GET",auth:!!e,token:e})}updateSettings(e,s){return this.expressRequest("/api/settings",{method:"PATCH",auth:!!s,token:s,body:JSON.stringify(e)})}getAccounts(e){return this.expressRequest("/api/accounts",{method:"GET",auth:!!e,token:e})}disconnectAccount(e,s){return this.expressRequest("/api/accounts/disconnect",{method:"POST",auth:!!s,token:s,body:JSON.stringify({accountId:e})})}getRules(e){return this.expressRequest("/api/rules",{method:"GET",auth:!!e,token:e})}createRule(e,s){return this.expressRequest("/api/rules",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}updateRule(e,s,i){return this.expressRequest(`/api/rules/${e}`,{method:"PATCH",auth:!!i,token:i,body:JSON.stringify(s)})}deleteRule(e,s){return this.expressRequest(`/api/rules/${e}`,{method:"DELETE",auth:!!s,token:s})}toggleRule(e,s){return this.expressRequest(`/api/rules/${e}/toggle`,{method:"POST",auth:!!s,token:s})}getStats(e){return this.expressRequest("/api/stats",{method:"GET",auth:!!e,token:e})}getProfile(e){return this.edgeRequest("/api-v1-profile",{method:"GET",auth:!!e,token:e})}updateProfile(e,s){return this.edgeRequest("/api-v1-profile",{method:"PATCH",auth:!!s,token:s,body:JSON.stringify(e)})}getChatProviders(e){return this.expressRequest("/api/sdk/providers/chat",{method:"GET",auth:!!e,token:e})}getEmbedProviders(e){return this.expressRequest("/api/sdk/providers/embed",{method:"GET",auth:!!e,token:e})}testLlm(e,s){return this.expressRequest("/api/sdk/test-llm",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}getGmailAuthUrl(e,s,i){return this.expressRequest("/api/accounts/gmail/auth-url",{method:"POST",auth:!!i,token:i,body:JSON.stringify({clientId:e,clientSecret:s})})}connectGmail(e,s,i,l){return this.expressRequest("/api/accounts/gmail/connect",{method:"POST",auth:!!l,token:l,body:JSON.stringify({authCode:e,clientId:s,clientSecret:i})})}getGoogleDriveAuthUrl(e,s){return this.expressRequest("/api/accounts/google-drive/auth-url",{method:"POST",auth:!!s,token:s,body:JSON.stringify({clientId:e})})}connectGoogleDrive(e,s,i,l){return this.expressRequest("/api/accounts/google-drive/connect",{method:"POST",auth:!!l,token:l,body:JSON.stringify({authCode:e,clientId:s,clientSecret:i})})}startMicrosoftDeviceFlow(e,s,i){return this.expressRequest("/api/accounts/microsoft/device-flow",{method:"POST",auth:!!i,token:i,body:JSON.stringify({clientId:e,tenantId:s})})}pollMicrosoftDeviceCode(e,s,i,l){return this.expressRequest("/api/accounts/microsoft/poll",{method:"POST",auth:!!l,token:l,body:JSON.stringify({deviceCode:e,clientId:s,tenantId:i})})}connectImap(e,s){return this.expressRequest("/api/accounts/imap/connect",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}setup(e){return this.edgeRequest("/setup",{method:"POST",body:JSON.stringify(e)})}getPolicies(e){return this.expressRequest("/api/policies",{auth:!!e,token:e})}savePolicy(e,s){return this.expressRequest("/api/policies",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}deletePolicy(e,s){return this.expressRequest(`/api/policies/${e}`,{method:"DELETE",auth:!!s,token:s})}patchPolicy(e,s,i){return this.expressRequest(`/api/policies/${e}`,{method:"PATCH",auth:!!i,token:i,body:JSON.stringify(s)})}reloadPolicies(e){return this.expressRequest("/api/policies/reload",{method:"POST",auth:!!e,token:e})}synthesizePolicy(e,s){return this.expressRequest("/api/policies/synthesize",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}getSDKChatProviders(){return this.expressRequest("/api/sdk/providers/chat")}getIngestions(e={},s){const i=new URLSearchParams;e.page&&i.set("page",String(e.page)),e.pageSize&&i.set("pageSize",String(e.pageSize)),e.q&&i.set("q",e.q);const l=i.toString()?`?${i}`:"";return this.expressRequest(`/api/ingestions${l}`,{auth:!!s,token:s})}uploadDocument(e,s){const i=new FormData;i.append("file",e);const l=ff(),u={"X-Supabase-Url":l.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":l.anonKey};return s&&(u.Authorization=`Bearer ${s}`),fetch(`${l.expressApiUrl}/api/ingestions/upload`,{method:"POST",headers:u,body:i}).then(d=>d.json())}rerunIngestion(e,s){return this.expressRequest(`/api/ingestions/${e}/rerun`,{method:"POST",auth:!!s,token:s})}matchIngestionToPolicy(e,s,i){const l=s.learn!==!1,u=s.rerun!==!1;return this.expressRequest(`/api/ingestions/${e}/match`,{method:"POST",auth:!!i,token:i,body:JSON.stringify({policy_id:s.policyId,learn:l,rerun:u,allow_side_effects:s.allowSideEffects===!0})})}suggestPolicyRefinement(e,s,i){return this.expressRequest(`/api/ingestions/${e}/refine-policy`,{method:"POST",auth:!!i,token:i,body:JSON.stringify({policy_id:s.policyId,provider:s.provider,model:s.model})})}deleteIngestion(e,s){return this.expressRequest(`/api/ingestions/${e}`,{method:"DELETE",auth:!!s,token:s})}updateIngestionTags(e,s,i){return this.expressRequest(`/api/ingestions/${e}/tags`,{method:"PATCH",auth:!!i,token:i,body:JSON.stringify({tags:s})})}summarizeIngestion(e,s){return this.expressRequest(`/api/ingestions/${e}/summarize`,{method:"POST",auth:!!s,token:s})}getBaselineConfig(e){return this.expressRequest("/api/baseline-config",{auth:!!e,token:e})}getBaselineConfigHistory(e){return this.expressRequest("/api/baseline-config/history",{auth:!!e,token:e})}saveBaselineConfig(e,s){return this.expressRequest("/api/baseline-config",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}activateBaselineConfig(e,s){return this.expressRequest(`/api/baseline-config/${e}/activate`,{method:"POST",auth:!!s,token:s})}suggestBaselineConfig(e,s){return this.expressRequest("/api/baseline-config/suggest",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}}const Ee=new _A;let ns=[],sm=new Set;function am(){sm.forEach(t=>t())}const ue={success:(t,e)=>Pc("success",t,e),error:(t,e)=>Pc("error",t,e),info:(t,e)=>Pc("info",t,e),warning:(t,e)=>Pc("warning",t,e)};function Pc(t,e,s=5e3){const i=ns.findIndex(u=>u.message===e&&u.type===t);if(i!==-1){const u=ns[i];ns=[...ns],ns[i]={...u,count:(u.count||1)+1,lastUpdated:Date.now()},am();return}const l=Math.random().toString(36).substr(2,9);ns=[...ns,{id:l,type:t,message:e,duration:s,count:1,lastUpdated:Date.now()}],am(),s>0&&setTimeout(()=>Kw(l),s)}function Kw(t){ns=ns.filter(e=>e.id!==t),am()}function NA(){const[,t]=v.useState(0);return v.useEffect(()=>{const e=()=>t(s=>s+1);return sm.add(e),()=>{sm.delete(e)}},[]),ns}const TA={success:Fk,error:Sn,info:Im,warning:Gw},EA={success:"bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400",error:"bg-destructive/10 border-destructive/20 text-destructive",info:"bg-blue-500/10 border-blue-500/20 text-blue-600 dark:text-blue-400",warning:"bg-yellow-500/10 border-yellow-500/20 text-yellow-600 dark:text-yellow-400"};function kA({toast:t}){const e=TA[t.type];return o.jsxs("div",{className:ve("flex items-start gap-3 p-4 rounded-lg border shadow-lg backdrop-blur-sm","animate-in slide-in-from-left-full duration-300",EA[t.type]),children:[o.jsxs("div",{className:"relative",children:[o.jsx(e,{className:"w-5 h-5 flex-shrink-0 mt-0.5"}),t.count&&t.count>1&&o.jsx("span",{className:"absolute -top-2 -right-2 bg-primary text-primary-foreground text-[10px] font-bold px-1.5 rounded-full border border-background scale-90 animate-in zoom-in duration-200",children:t.count})]}),o.jsx("p",{className:"text-sm flex-1",children:t.message}),o.jsx("button",{onClick:()=>Kw(t.id),className:"p-1 hover:bg-black/10 rounded transition-colors",children:o.jsx(zn,{className:"w-4 h-4"})})]})}function CA(){const t=NA();return t.length===0?null:o.jsx("div",{className:"fixed bottom-4 left-4 z-[100] flex flex-col-reverse gap-2 max-w-sm w-full",children:t.map(e=>o.jsx(kA,{toast:e},e.id))})}function AA({configSnapshot:t,configSource:e,setActivePage:s}){const[i,l]=v.useState(null),[u,d]=v.useState(!0),[h,m]=v.useState(!1),[p,y]=v.useState(!1),x=v.useRef(null),w=v.useCallback(async()=>{d(!0);try{const S=un();if(!S)return;const{data:_}=await S.auth.getSession(),E=_.session?.access_token??null;if(!E)return;const C=await Ee.getDashboardStats(E);C.data?.success&&l(C.data.stats)}catch(S){console.error("Failed to fetch dashboard stats",S)}finally{d(!1)}},[]);v.useEffect(()=>{w()},[w]);const j=async S=>{const _=Array.from(S);if(_.length){s("funnel"),y(!0);try{const E=un();if(!E)return;const{data:C}=await E.auth.getSession(),A=C.session?.access_token??null;if(!A)return;for(const k of _){ue.info(`Ingesting ${k.name}…`);const M=await Ee.uploadDocument?.(k,A);if(M?.success)if(M.ingestion?.status==="duplicate"){const P=M.ingestion.extracted?.original_filename??"a previous upload";ue.warning(`${k.name} is a duplicate of "${P}" — skipped.`)}else ue.success(`${k.name} → ${M.ingestion?.status}`);else ue.error(`Failed to ingest ${k.name}`)}await w()}finally{y(!1)}}},T=S=>{S.preventDefault(),m(!1),j(S.dataTransfer.files)};return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-12 animate-in fade-in duration-700",children:[o.jsxs("div",{className:"text-center space-y-3",children:[o.jsxs("h2",{className:"text-4xl font-black tracking-tight flex items-center justify-center gap-3",children:[o.jsx(ou,{className:"w-10 h-10 animate-pulse"}),"Command Center"]}),o.jsx("p",{className:"text-muted-foreground text-lg max-w-2xl mx-auto",children:"Central intelligence hub for document ingestion, routing, and synthetic knowledge."})]}),o.jsxs("div",{className:"w-full space-y-10",children:[o.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(zc,{title:"Documents Ingested",value:i?.totalDocuments,icon:o.jsx(Vm,{className:"w-5 h-5 text-blue-500"}),isLoading:u,colorClass:"bg-blue-500/10"}),o.jsx(zc,{title:"Active Policies",value:i?.activePolicies,icon:o.jsx(p0,{className:"w-5 h-5 text-emerald-500"}),isLoading:u,colorClass:"bg-emerald-500/10"}),o.jsx(zc,{title:"Knowledge Chunks",value:i?.ragChunks,icon:o.jsx(Eu,{className:"w-5 h-5 text-purple-500"}),isLoading:u,colorClass:"bg-purple-500/10"}),o.jsx(zc,{title:"Automation Runs",value:i?.automationRuns,icon:o.jsx(dr,{className:"w-5 h-5 text-amber-500"}),isLoading:u,colorClass:"bg-amber-500/10"})]}),o.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[o.jsx("div",{className:"lg:col-span-2",children:o.jsxs("div",{onDragOver:S=>{S.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:T,onClick:()=>x.current?.click(),className:ve("h-full rounded-2xl border-2 border-dashed transition-all cursor-pointer flex flex-col items-center justify-center gap-4 py-16",h?"border-primary bg-primary/5 scale-[1.01]":"border-muted-foreground/20 hover:border-primary/50 hover:bg-muted/30"),children:[o.jsx("input",{ref:x,type:"file",multiple:!0,hidden:!0,onChange:S=>S.target.files&&j(S.target.files)}),p?o.jsx(rt,{className:"w-12 h-12 animate-spin text-primary"}):o.jsx(tm,{className:ve("w-12 h-12 transition-colors",h?"text-primary":"text-muted-foreground/50")}),o.jsxs("div",{className:"text-center space-y-1",children:[o.jsx("p",{className:"text-lg font-medium text-foreground",children:h?"Drop to ingest...":"Drag & drop files to ingest"}),o.jsx("p",{className:"text-sm text-muted-foreground/60",children:"Supports .pdf, .docx, .md, .txt (up to 20MB)"})]})]})}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs(ht,{className:"flex-1 cursor-pointer hover:border-primary/50 hover:bg-muted/30 transition-all flex flex-col items-center justify-center p-6 text-center shadow-sm",onClick:()=>s("chat"),children:[o.jsx("div",{className:"w-12 h-12 rounded-xl bg-indigo-500/10 flex items-center justify-center mb-4",children:o.jsx(cu,{className:"w-6 h-6 text-indigo-500"})}),o.jsx("h3",{className:"font-bold mb-1",children:"Chat with Data"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask questions against your vectorized knowledge base."})]}),o.jsxs(ht,{className:"flex-1 cursor-pointer hover:border-primary/50 hover:bg-muted/30 transition-all flex flex-col items-center justify-center p-6 text-center shadow-sm",onClick:()=>s("policies"),children:[o.jsx("div",{className:"w-12 h-12 rounded-xl bg-orange-500/10 flex items-center justify-center mb-4",children:o.jsx(p0,{className:"w-6 h-6 text-orange-500"})}),o.jsx("h3",{className:"font-bold mb-1",children:"Create Policy"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Define a new routing and automation contract."})]})]})]})]})]})}function zc({title:t,value:e,icon:s,isLoading:i,colorClass:l}){return o.jsx(ht,{className:"shadow-sm",children:o.jsxs(xt,{className:"p-6",children:[o.jsx("div",{className:"flex items-center justify-between mb-4",children:o.jsx("div",{className:ve("w-10 h-10 rounded-xl flex items-center justify-center",l),children:s})}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("p",{className:"text-sm text-muted-foreground font-medium",children:t}),i?o.jsx("div",{className:"h-8 w-16 bg-muted animate-pulse rounded-md"}):o.jsx("p",{className:"text-3xl font-black",children:e!==void 0?e.toLocaleString():"0"})]})]})})}function y0(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Au(...t){return e=>{let s=!1;const i=t.map(l=>{const u=y0(l,e);return!s&&typeof u=="function"&&(s=!0),u});if(s)return()=>{for(let l=0;l<i.length;l++){const u=i[l];typeof u=="function"?u():y0(t[l],null)}}}}function si(...t){return v.useCallback(Au(...t),t)}var RA=Symbol.for("react.lazy"),fu=Mm[" use ".trim().toString()];function OA(t){return typeof t=="object"&&t!==null&&"then"in t}function Yw(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===RA&&"_payload"in t&&OA(t._payload)}function Xw(t){const e=DA(t),s=v.forwardRef((i,l)=>{let{children:u,...d}=i;Yw(u)&&typeof fu=="function"&&(u=fu(u._payload));const h=v.Children.toArray(u),m=h.find(zA);if(m){const p=m.props.children,y=h.map(x=>x===m?v.Children.count(p)>1?v.Children.only(null):v.isValidElement(p)?p.props.children:null:x);return o.jsx(e,{...d,ref:l,children:v.isValidElement(p)?v.cloneElement(p,void 0,y):null})}return o.jsx(e,{...d,ref:l,children:u})});return s.displayName=`${t}.Slot`,s}var MA=Xw("Slot");function DA(t){const e=v.forwardRef((s,i)=>{let{children:l,...u}=s;if(Yw(l)&&typeof fu=="function"&&(l=fu(l._payload)),v.isValidElement(l)){const d=UA(l),h=LA(u,l.props);return l.type!==v.Fragment&&(h.ref=i?Au(i,d):d),v.cloneElement(l,h)}return v.Children.count(l)>1?v.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var PA=Symbol("radix.slottable");function zA(t){return v.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===PA}function LA(t,e){const s={...e};for(const i in e){const l=t[i],u=e[i];/^on[A-Z]/.test(i)?l&&u?s[i]=(...h)=>{const m=u(...h);return l(...h),m}:l&&(s[i]=l):i==="style"?s[i]={...l,...u}:i==="className"&&(s[i]=[l,u].filter(Boolean).join(" "))}return{...t,...s}}function UA(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning;return s?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning,s?t.props.ref:t.props.ref||t.ref)}const v0=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,x0=xw,qm=(t,e)=>s=>{var i;if(e?.variants==null)return x0(t,s?.class,s?.className);const{variants:l,defaultVariants:u}=e,d=Object.keys(l).map(p=>{const y=s?.[p],x=u?.[p];if(y===null)return null;const w=v0(y)||v0(x);return l[p][w]}),h=s&&Object.entries(s).reduce((p,y)=>{let[x,w]=y;return w===void 0||(p[x]=w),p},{}),m=e==null||(i=e.compoundVariants)===null||i===void 0?void 0:i.reduce((p,y)=>{let{class:x,className:w,...j}=y;return Object.entries(j).every(T=>{let[S,_]=T;return Array.isArray(_)?_.includes({...u,...h}[S]):{...u,...h}[S]===_})?[...p,x,w]:p},[]);return x0(t,d,m,s?.class,s?.className)},BA=qm("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[color,box-shadow] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 focus-visible:ring-4 focus-visible:outline-1 aria-invalid:focus-visible:ring-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-sm hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90",outline:"border border-input bg-background shadow-xs hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),ae=v.forwardRef(({className:t,variant:e,size:s,asChild:i=!1,...l},u)=>{const d=i?MA:"button";return o.jsx(d,{className:ve(BA({variant:e,size:s,className:t})),ref:u,...l})});ae.displayName="Button";const _e=v.forwardRef(({className:t,type:e,...s},i)=>o.jsx("input",{type:e,className:ve("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:i,...s}));_e.displayName="Input";var Ww=tw();const VA=Zb(Ww);var IA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],$A=IA.reduce((t,e)=>{const s=Xw(`Primitive.${e}`),i=v.forwardRef((l,u)=>{const{asChild:d,...h}=l,m=d?s:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(m,{...h,ref:u})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{}),qA="Label",Jw=v.forwardRef((t,e)=>o.jsx($A.label,{...t,ref:e,onMouseDown:s=>{s.target.closest("button, input, select, textarea")||(t.onMouseDown?.(s),!s.defaultPrevented&&s.detail>1&&s.preventDefault())}}));Jw.displayName=qA;var HA=Jw;function Je({className:t,...e}){return o.jsx(HA,{"data-slot":"label",className:ve("flex items-center gap-2 text-sm leading-none font-medium select-none text-muted-foreground group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...e})}const GA=qm("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Mt({className:t,variant:e,...s}){return o.jsx("div",{className:ve(GA({variant:e}),t),...s})}const FA=qm("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),jn=v.forwardRef(({className:t,variant:e,...s},i)=>o.jsx("div",{ref:i,role:"alert",className:ve(FA({variant:e}),t),...s}));jn.displayName="Alert";const Hm=v.forwardRef(({className:t,...e},s)=>o.jsx("h5",{ref:s,className:ve("mb-1 font-medium leading-none tracking-tight",t),...e}));Hm.displayName="AlertTitle";const _n=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("text-sm [&_p]:leading-relaxed",t),...e}));_n.displayName="AlertDescription";function KA({supabase:t,initStatus:e,sessionStatus:s,sessionEmail:i,onRefresh:l}){const[u,d]=v.useState(""),[h,m]=v.useState(""),[p,y]=v.useState(""),[x,w]=v.useState(""),[j,T]=v.useState(!1),[S,_]=v.useState(null),E=e==="empty";async function C(){T(!0),_(null);const{error:P}=await t.auth.signInWithPassword({email:u,password:h});P?_(P.message):l(),T(!1)}async function A(){T(!0),_(null);try{const P=await Ee.setup({email:u,password:h,first_name:p,last_name:x});if(P.error)throw new Error(typeof P.error=="string"?P.error:P.error.message);const{error:B}=await t.auth.signInWithPassword({email:u,password:h});if(B)throw B;l()}catch(P){_(P.message||"Failed to initialize foundation.")}finally{T(!1)}}async function k(){T(!0),_(null);const{error:P}=await t.auth.signUp({email:u,password:h,options:{data:{first_name:p,last_name:x}}});P?_(P.message):l(),T(!1)}async function M(){T(!0),await t.auth.signOut(),l(),T(!1)}return s==="authenticated"?o.jsxs("div",{className:"space-y-4 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex items-center gap-4 p-4 rounded-xl bg-primary/5 border border-primary/10",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-primary flex items-center justify-center text-primary-foreground",children:o.jsx(ku,{className:"w-5 h-5"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-xs font-bold uppercase tracking-widest text-muted-foreground leading-none mb-1",children:"Authenticated as"}),o.jsx("p",{className:"text-sm font-medium truncate",children:i})]})]}),e==="missing_view"&&o.jsxs(jn,{variant:"destructive",className:"bg-destructive/5 text-destructive border-destructive/20",children:[o.jsx(uu,{className:"w-4 h-4"}),o.jsx(_n,{className:"text-xs",children:"Database views missing. Foundation may be corrupted."})]}),o.jsxs(ae,{variant:"outline",className:"w-full h-11 hover:bg-destructive hover:text-destructive-reveal group transition-all duration-300",onClick:M,disabled:j,children:[j?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(Iw,{className:"w-4 h-4 mr-2 group-hover:rotate-180 transition-transform duration-500"}),"Logout Protocol"]})]}):o.jsxs("div",{className:"space-y-4 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"grid gap-4",children:[E&&o.jsxs("div",{className:"grid grid-cols-2 gap-4 animate-in slide-in-from-top-2 duration-300",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-firstname",children:"First Name"}),o.jsx(_e,{id:"auth-firstname",placeholder:"Agent",value:p,onChange:P=>y(P.target.value),className:"h-10"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-lastname",children:"Last Name"}),o.jsx(_e,{id:"auth-lastname",placeholder:"Zero",value:x,onChange:P=>w(P.target.value),className:"h-10"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-email",children:"Email Address"}),o.jsxs("div",{className:"relative",children:[o.jsx(Vo,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(_e,{id:"auth-email",type:"email",placeholder:"admin@example.com",value:u,onChange:P=>d(P.target.value),className:"pl-9 h-10"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-password",children:"Security Key"}),o.jsxs("div",{className:"relative",children:[o.jsx(Zo,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(_e,{id:"auth-password",type:"password",placeholder:"••••••••",value:h,onChange:P=>m(P.target.value),className:"pl-9 h-10",autoComplete:E?"new-password":"current-password"})]})]})]}),S&&o.jsx(jn,{variant:"destructive",className:"py-2 px-3",children:o.jsx(_n,{className:"text-[11px] leading-relaxed italic",children:S})}),o.jsx("div",{className:"pt-2",children:E?o.jsxs(ae,{className:"w-full h-11 shadow-lg shadow-primary/20",onClick:A,disabled:j||!u||!h||!p,children:[j?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(ya,{className:"w-4 h-4 mr-2"}),"Initialize Primary Admin"]}):o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs(ae,{className:"h-10",onClick:C,disabled:j||!u||!h,children:[j?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(Vw,{className:"w-4 h-4 mr-2"}),"Login"]}),o.jsxs(ae,{variant:"secondary",className:"h-10",onClick:k,disabled:j||!u||!h,children:[o.jsx(pA,{className:"w-4 h-4 mr-2"}),"Enroll"]})]})}),o.jsx("p",{className:"text-[10px] text-center text-muted-foreground uppercase tracking-widest font-bold opacity-50 pt-2",children:E?"Foundation Assembly Phase":"Foundation Access Required"})]})}const ha="0.1.14",YA="20260302000000";async function XA(t,e){const s=Promise.resolve(t);let i=null;const l=new Promise((u,d)=>{i=setTimeout(()=>{d(new Error(`Operation timed out after ${e}ms`))},e)});try{return await Promise.race([s,l])}finally{i&&clearTimeout(i)}}async function WA(t){try{const{data:e,error:s}=await XA(t.rpc("get_latest_migration_timestamp"),12e3);if(s)return s.code==="42883"?{latestMigrationTimestamp:"0"}:{latestMigrationTimestamp:null};const i=e??null;return i&&i>="29990000000000"?{latestMigrationTimestamp:null}:{latestMigrationTimestamp:i}}catch{return{latestMigrationTimestamp:null}}}async function Qw(t){const e=await WA(t);return!e.latestMigrationTimestamp||e.latestMigrationTimestamp.trim()===""?{needsMigration:!0,appVersion:ha,latestMigrationTimestamp:e.latestMigrationTimestamp,message:"Database migration state unknown."}:YA>e.latestMigrationTimestamp?{needsMigration:!0,appVersion:ha,latestMigrationTimestamp:e.latestMigrationTimestamp,message:`Database is behind (${e.latestMigrationTimestamp}).`}:{needsMigration:!1,appVersion:ha,latestMigrationTimestamp:e.latestMigrationTimestamp,message:"Database schema is up-to-date."}}function JA({supabase:t,sessionEmail:e,sessionStatus:s,initStatus:i,configSnapshot:l,configSource:u,onRefresh:d,onLaunchSetup:h,onResetSetup:m}){const[p,y]=v.useState("profile"),[x,w]=v.useState(null),[j,T]=v.useState(!1);async function S(){if(!t)return;T(!0);const{data:{user:C}}=await t.auth.getUser();if(C){const{data:A}=await t.from("profiles").select("*").eq("id",C.id).single();A&&w(A)}T(!1)}v.useEffect(()=>{s==="authenticated"&&t&&S()},[s,t]);const _=[{id:"profile",label:"Profile",icon:ku},{id:"security",label:"Security",icon:ya},{id:"supabase",label:"Supabase",icon:Eu}];async function E(){t&&(await t.auth.signOut(),d())}return o.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-in fade-in duration-700",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h1",{className:"text-4xl font-black tracking-tight",children:"Account Settings"}),o.jsx("p",{className:"text-muted-foreground text-lg",children:"Manage your profile and foundational preferences."})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-12 items-start",children:[o.jsxs("aside",{className:"w-full md:w-72 flex flex-col gap-8 shrink-0",children:[o.jsx("nav",{className:"space-y-1",children:_.map(C=>{const A=C.icon,k=p===C.id;return o.jsxs("button",{onClick:()=>y(C.id),className:ve("w-full flex items-center gap-3 px-4 py-3 text-sm font-bold rounded-xl transition-all duration-300",k?"bg-foreground text-background shadow-lg shadow-foreground/10":"text-muted-foreground hover:bg-muted/60 hover:text-foreground"),children:[o.jsx(A,{className:ve("w-5 h-5",k?"text-background":"text-muted-foreground/60")}),C.label]},C.id)})}),o.jsxs("div",{className:"pt-8 border-t space-y-6",children:[o.jsxs("button",{onClick:E,className:"group w-full flex items-center gap-3 px-4 py-2 text-sm font-bold rounded-xl transition-all duration-300 text-destructive hover:bg-destructive/10",children:[o.jsx(Iw,{className:"w-5 h-5 transition-transform group-hover:translate-x-1"}),"Logout"]}),o.jsxs("div",{className:"px-4",children:[o.jsx("p",{className:"text-[10px] font-black text-muted-foreground/40 uppercase tracking-widest mb-1",children:"Version"}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/60",children:["v",ha]})]})]})]}),o.jsxs("div",{className:"flex-1 w-full animate-in slide-in-from-right-4 duration-500",children:[p==="profile"&&o.jsx(QA,{sessionEmail:e,sessionStatus:s,supabase:t,initStatus:i,profile:x,onProfileUpdate:S,onRefresh:d,isLoading:j}),p==="security"&&o.jsx(ZA,{supabase:t}),p==="supabase"&&o.jsx(eR,{configSnapshot:l,configSource:u,onLaunchSetup:h,onResetSetup:m})]})]})]})}function QA({sessionEmail:t,sessionStatus:e,supabase:s,initStatus:i,profile:l,onProfileUpdate:u,onRefresh:d,isLoading:h}){const[m,p]=v.useState(""),[y,x]=v.useState(""),[w,j]=v.useState(!0),[T,S]=v.useState(!1),[_,E]=v.useState(!1);v.useEffect(()=>{l&&(p(l.first_name||""),x(l.last_name||""))},[l]);const C=async()=>{if(!s||!l)return;S(!0);const{error:k}=await s.from("profiles").update({first_name:m,last_name:y}).eq("id",l.id);k||u(),S(!1)},A=async k=>{const M=k.target.files?.[0];if(!(!M||!s||!l)){E(!0);try{const P=M.name.split(".").pop(),B=`${l.id}/${Math.random()}.${P}`,{error:R}=await s.storage.from("avatars").upload(B,M);if(R)throw R;const{data:{publicUrl:I}}=s.storage.from("avatars").getPublicUrl(B);await s.from("profiles").update({avatar_url:I}).eq("id",l.id),u()}catch(P){console.error("Upload error:",P)}finally{E(!1)}}};return o.jsxs(ht,{className:"border-border/40 shadow-xl shadow-black/5 bg-card/50 backdrop-blur-sm overflow-hidden",children:[o.jsxs(zt,{className:"p-8 border-b bg-muted/20",children:[o.jsx(Lt,{className:"text-2xl font-black",children:"Profile Information"}),o.jsx(wn,{className:"text-base",children:"Update your personal foundation details."})]}),o.jsx(xt,{className:"p-8 space-y-10",children:h?o.jsx("div",{className:"flex items-center justify-center py-12",children:o.jsx(rt,{className:"w-8 h-8 animate-spin text-primary"})}):e==="authenticated"?o.jsxs("div",{className:"space-y-10",children:[o.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-8",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("div",{className:"w-32 h-32 rounded-full bg-primary/10 border-4 border-background shadow-2xl overflow-hidden flex items-center justify-center",children:l?.avatar_url?o.jsx("img",{src:l.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):t?o.jsx("span",{className:"text-4xl font-black text-primary",children:t.charAt(0).toUpperCase()}):o.jsx(ku,{className:"w-12 h-12 text-primary/40"})}),o.jsxs("label",{className:"absolute bottom-1 right-1 h-10 w-10 rounded-full bg-background border shadow-lg flex items-center justify-center hover:scale-110 transition-transform cursor-pointer",children:[_?o.jsx(rt,{className:"w-4 h-4 animate-spin text-muted-foreground"}):o.jsx(Uk,{className:"w-5 h-5 text-muted-foreground"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:A,disabled:_})]})]}),o.jsxs("div",{className:"flex-1 w-full grid grid-cols-1 sm:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"firstName",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"First Name"}),o.jsx(_e,{id:"firstName",placeholder:"Trung",value:m,onChange:k=>p(k.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"lastName",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"Last Name"}),o.jsx(_e,{id:"lastName",placeholder:"Le",value:y,onChange:k=>x(k.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]}),o.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[o.jsx(Je,{htmlFor:"email",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"Email Address"}),o.jsx(_e,{id:"email",value:t||"",disabled:!0,className:"h-12 rounded-xl bg-muted/40 border-border/40 opacity-70 cursor-not-allowed"}),o.jsx("p",{className:"text-[10px] text-muted-foreground/60 font-bold ml-1",children:"This is your login email and cannot be changed."})]})]})]}),o.jsxs("div",{className:"pt-8 border-t flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h4",{className:"text-base font-bold",children:"Sound & Haptic Feedback"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Play chimes and haptic pulses for system events."})]}),o.jsxs(ae,{variant:w?"default":"outline",className:ve("h-11 px-6 rounded-xl font-bold transition-all",w?"shadow-lg shadow-primary/20":""),onClick:()=>j(!w),children:[w?o.jsx(nm,{className:"w-4 h-4 mr-2"}):o.jsx(Fw,{className:"w-4 h-4 mr-2"}),w?"Enabled":"Disabled"]})]})]}):o.jsxs("div",{className:"py-8",children:[o.jsxs("div",{className:"flex items-center gap-3 border-b pb-4 mb-6",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary",children:o.jsx(ya,{className:"w-6 h-6"})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-bold",children:"Authentication Gateway"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Access your foundational profile."})]})]}),s&&o.jsx(KA,{supabase:s,initStatus:i,sessionStatus:e,sessionEmail:t,onRefresh:d})]})}),e==="authenticated"&&!h&&o.jsx(Tu,{className:"bg-muted/20 p-8 flex justify-end",children:o.jsxs(ae,{className:"h-12 px-8 rounded-xl font-bold shadow-xl shadow-primary/20",onClick:C,disabled:T,children:[T?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(VC,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})}function ZA({supabase:t}){const[e,s]=v.useState(""),[i,l]=v.useState(""),[u,d]=v.useState(!1),[h,m]=v.useState(null),p=async()=>{if(!t)return;if(e!==i){m({type:"error",msg:"Passwords do not match."});return}if(e.length<8){m({type:"error",msg:"Password must be at least 8 characters."});return}d(!0),m(null);const{error:y}=await t.auth.updateUser({password:e});y?m({type:"error",msg:y.message}):(m({type:"success",msg:"Password updated successfully."}),s(""),l("")),d(!1)};return o.jsxs(ht,{className:"border-border/40 shadow-xl shadow-black/5 bg-card/50 backdrop-blur-sm overflow-hidden",children:[o.jsxs(zt,{className:"p-8 border-b bg-muted/20",children:[o.jsx(Lt,{className:"text-2xl font-black",children:"Security Protocol"}),o.jsx(wn,{className:"text-base",children:"Manage your foundation credentials and access keys."})]}),o.jsxs(xt,{className:"p-8 space-y-8",children:[h&&o.jsxs(jn,{variant:h.type==="error"?"destructive":"default",className:ve("animate-in fade-in slide-in-from-top-2 duration-300",h.type==="success"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":""),children:[h.type==="success"?o.jsx(os,{className:"h-4 w-4"}):o.jsx(uu,{className:"h-4 w-4"}),o.jsx(_n,{className:"text-sm font-bold",children:h.msg})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-8",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"newPass",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"New Password"}),o.jsx(_e,{id:"newPass",type:"password",placeholder:"••••••••",value:e,onChange:y=>s(y.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"confirmPass",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"Confirm Password"}),o.jsx(_e,{id:"confirmPass",type:"password",placeholder:"••••••••",value:i,onChange:y=>l(y.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]})]}),o.jsxs("div",{className:"bg-muted/30 p-6 rounded-2xl border border-border/40 space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary",children:o.jsx(uu,{className:"w-5 h-5"})}),o.jsx("h5",{className:"font-bold",children:"Security Tip"})]}),o.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Use a password at least 12 characters long with a mix of letters, numbers, and symbols to ensure your foundational data remains secure."})]})]})]}),o.jsx(Tu,{className:"bg-muted/20 p-8 flex justify-end",children:o.jsxs(ae,{className:"h-12 px-8 rounded-xl font-bold shadow-xl shadow-primary/20",onClick:p,disabled:u||!e||!i,children:[u?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(Zo,{className:"w-4 h-4 mr-2"}),"Update Password"]})})]})}function eR({configSnapshot:t,configSource:e,onLaunchSetup:s,onResetSetup:i}){return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-700",children:[o.jsxs("div",{className:"flex items-center gap-3 border-b pb-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary",children:o.jsx(Eu,{className:"w-6 h-6"})}),o.jsxs("div",{className:"flex-1",children:[o.jsx("h3",{className:"text-lg font-bold",children:"Supabase Configuration"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Primary storage and identity gateway."})]}),o.jsxs(Mt,{variant:"secondary",className:"text-[10px] font-black uppercase tracking-widest px-3 py-1",children:["Source: ",e]})]}),o.jsxs(ht,{className:"border-border/40 shadow-sm bg-card/50 backdrop-blur-sm",children:[o.jsx(xt,{className:"p-8 space-y-8",children:t?o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("span",{className:"text-[10px] font-black uppercase text-muted-foreground tracking-widest pl-1",children:"API Endpoint"}),o.jsx("div",{className:"bg-muted/30 p-4 rounded-2xl border border-border/40 backdrop-blur-sm shadow-inner",children:o.jsx("p",{className:"text-sm font-semibold truncate text-foreground/80",children:t.url})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("span",{className:"text-[10px] font-black uppercase text-muted-foreground tracking-widest pl-1",children:"Project Identifier"}),o.jsx("div",{className:"bg-muted/30 p-4 rounded-2xl border border-border/40 font-mono shadow-inner",children:o.jsx("p",{className:"text-sm font-semibold text-foreground/80",children:t.url.split("//")[1]?.split(".")[0]||"Unknown"})})]}),o.jsxs("div",{className:"md:col-span-2 space-y-2",children:[o.jsx("span",{className:"text-[10px] font-black uppercase text-muted-foreground tracking-widest pl-1",children:"Service Role Access (Masked)"}),o.jsxs("div",{className:"bg-muted/30 p-4 rounded-2xl border border-border/40 flex items-center justify-between shadow-inner",children:[o.jsxs("p",{className:"text-sm font-mono text-muted-foreground",children:[t.anonKey.slice(0,6),"...",t.anonKey.slice(-6)]}),o.jsx(Mt,{variant:"outline",className:"text-[9px] font-bold",children:"Standard Key"})]})]})]}):o.jsxs(jn,{className:"bg-amber-500/5 border-amber-500/20 text-amber-600 dark:text-amber-400 p-6 rounded-2xl shadow-sm",children:[o.jsx(Sn,{className:"w-5 h-5"}),o.jsx(Hm,{className:"font-bold mb-1",children:"Infrastructure Standby"}),o.jsx(_n,{className:"text-sm opacity-90",children:"The foundation has not been initialized. You must run the setup wizard to continue."})]})}),o.jsxs(Tu,{className:"bg-muted/20 p-8 flex gap-4 border-t",children:[o.jsxs(ae,{variant:t?"outline":"default",className:"flex-1 h-12 rounded-xl font-bold shadow-sm",onClick:s,children:[t?o.jsx(WC,{className:"w-4 h-4 mr-2"}):o.jsx(Ja,{className:"w-4 h-4 mr-2"}),t?"Run Setup Wizard":"Launch Initializer"]}),t&&o.jsx(ae,{variant:"ghost",size:"icon",className:"h-12 w-12 rounded-xl text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors",onClick:i,title:"Reset All Configuration",children:o.jsx(PC,{className:"w-5 h-5"})})]})]}),o.jsxs("div",{className:"space-y-6 pt-4",children:[o.jsxs("div",{className:"flex items-center gap-3 border-b pb-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-destructive/10 flex items-center justify-center text-destructive",children:o.jsx(Sn,{className:"w-6 h-6"})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-bold text-destructive",children:"Advanced Maintenance"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Destructive actions and system-level overrides."})]})]}),o.jsx(ht,{className:"border-destructive/20 bg-destructive/5 overflow-hidden shadow-sm",children:o.jsxs(xt,{className:"p-8",children:[o.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Fully resetting the foundation will purge all local storage cached parameters. This action is irreversible and will force a fresh bootstrap flow upon next launch."}),o.jsx(ae,{variant:"link",className:"px-0 text-destructive h-auto text-xs font-black uppercase tracking-widest mt-4 hover:no-underline hover:opacity-70 transition-opacity",onClick:i,children:"Wipe Local Foundation Buffer"})]})})]})]})}const tR={theme:"system",setTheme:()=>null},Zw=v.createContext(tR);function nR({children:t,defaultTheme:e="system",storageKey:s="vite-ui-theme"}){const[i,l]=v.useState(()=>localStorage.getItem(s)||e);v.useEffect(()=>{const d=window.document.documentElement;if(d.classList.remove("light","dark"),i==="system"){const h=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";d.classList.add(h);return}d.classList.add(i)},[i]);const u=v.useMemo(()=>({theme:i,setTheme:d=>{localStorage.setItem(s,d),l(d)}}),[i,s]);return o.jsx(Zw.Provider,{value:u,children:t})}const sR=()=>{const t=v.useContext(Zw);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function e1(){const{setTheme:t,theme:e}=sR();return o.jsxs(ae,{variant:"ghost",size:"icon",onClick:()=>t(e==="dark"?"light":"dark"),className:"text-muted-foreground hover:bg-muted/60 transition-all duration-300 h-9 w-9 rounded-full",title:`Switch to ${e==="dark"?"light":"dark"} mode`,children:[e==="dark"?o.jsx(nA,{className:"h-[1.2rem] w-[1.2rem]"}):o.jsx(CC,{className:"h-[1.2rem] w-[1.2rem]"}),o.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}function fa(t,e,{checkForDefaultPrevented:s=!0}={}){return function(l){if(t?.(l),s===!1||!l.defaultPrevented)return e?.(l)}}function aR(t,e){const s=v.createContext(e),i=u=>{const{children:d,...h}=u,m=v.useMemo(()=>h,Object.values(h));return o.jsx(s.Provider,{value:m,children:d})};i.displayName=t+"Provider";function l(u){const d=v.useContext(s);if(d)return d;if(e!==void 0)return e;throw new Error(`\`${u}\` must be used within \`${t}\``)}return[i,l]}function iR(t,e=[]){let s=[];function i(u,d){const h=v.createContext(d),m=s.length;s=[...s,d];const p=x=>{const{scope:w,children:j,...T}=x,S=w?.[t]?.[m]||h,_=v.useMemo(()=>T,Object.values(T));return o.jsx(S.Provider,{value:_,children:j})};p.displayName=u+"Provider";function y(x,w){const j=w?.[t]?.[m]||h,T=v.useContext(j);if(T)return T;if(d!==void 0)return d;throw new Error(`\`${x}\` must be used within \`${u}\``)}return[p,y]}const l=()=>{const u=s.map(d=>v.createContext(d));return function(h){const m=h?.[t]||u;return v.useMemo(()=>({[`__scope${t}`]:{...h,[t]:m}}),[h,m])}};return l.scopeName=t,[i,rR(l,...e)]}function rR(...t){const e=t[0];if(t.length===1)return e;const s=()=>{const i=t.map(l=>({useScope:l(),scopeName:l.scopeName}));return function(u){const d=i.reduce((h,{useScope:m,scopeName:p})=>{const x=m(u)[`__scope${p}`];return{...h,...x}},{});return v.useMemo(()=>({[`__scope${e.scopeName}`]:d}),[d])}};return s.scopeName=e.scopeName,s}var qo=globalThis?.document?v.useLayoutEffect:()=>{},oR=Mm[" useId ".trim().toString()]||(()=>{}),lR=0;function mf(t){const[e,s]=v.useState(oR());return qo(()=>{s(i=>i??String(lR++))},[t]),t||(e?`radix-${e}`:"")}var cR=Mm[" useInsertionEffect ".trim().toString()]||qo;function uR({prop:t,defaultProp:e,onChange:s=()=>{},caller:i}){const[l,u,d]=dR({defaultProp:e,onChange:s}),h=t!==void 0,m=h?t:l;{const y=v.useRef(t!==void 0);v.useEffect(()=>{const x=y.current;x!==h&&console.warn(`${i} is changing from ${x?"controlled":"uncontrolled"} to ${h?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=h},[h,i])}const p=v.useCallback(y=>{if(h){const x=hR(y)?y(t):y;x!==t&&d.current?.(x)}else u(y)},[h,t,u,d]);return[m,p]}function dR({defaultProp:t,onChange:e}){const[s,i]=v.useState(t),l=v.useRef(s),u=v.useRef(e);return cR(()=>{u.current=e},[e]),v.useEffect(()=>{l.current!==s&&(u.current?.(s),l.current=s)},[s,l]),[s,i,u]}function hR(t){return typeof t=="function"}function fR(t){const e=mR(t),s=v.forwardRef((i,l)=>{const{children:u,...d}=i,h=v.Children.toArray(u),m=h.find(gR);if(m){const p=m.props.children,y=h.map(x=>x===m?v.Children.count(p)>1?v.Children.only(null):v.isValidElement(p)?p.props.children:null:x);return o.jsx(e,{...d,ref:l,children:v.isValidElement(p)?v.cloneElement(p,void 0,y):null})}return o.jsx(e,{...d,ref:l,children:u})});return s.displayName=`${t}.Slot`,s}function mR(t){const e=v.forwardRef((s,i)=>{const{children:l,...u}=s;if(v.isValidElement(l)){const d=vR(l),h=yR(u,l.props);return l.type!==v.Fragment&&(h.ref=i?Au(i,d):d),v.cloneElement(l,h)}return v.Children.count(l)>1?v.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var pR=Symbol("radix.slottable");function gR(t){return v.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===pR}function yR(t,e){const s={...e};for(const i in e){const l=t[i],u=e[i];/^on[A-Z]/.test(i)?l&&u?s[i]=(...h)=>{const m=u(...h);return l(...h),m}:l&&(s[i]=l):i==="style"?s[i]={...l,...u}:i==="className"&&(s[i]=[l,u].filter(Boolean).join(" "))}return{...t,...s}}function vR(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning;return s?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning,s?t.props.ref:t.props.ref||t.ref)}var xR=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Os=xR.reduce((t,e)=>{const s=fR(`Primitive.${e}`),i=v.forwardRef((l,u)=>{const{asChild:d,...h}=l,m=d?s:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(m,{...h,ref:u})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{});function bR(t,e){t&&Ww.flushSync(()=>t.dispatchEvent(e))}function Ho(t){const e=v.useRef(t);return v.useEffect(()=>{e.current=t}),v.useMemo(()=>(...s)=>e.current?.(...s),[])}function wR(t,e=globalThis?.document){const s=Ho(t);v.useEffect(()=>{const i=l=>{l.key==="Escape"&&s(l)};return e.addEventListener("keydown",i,{capture:!0}),()=>e.removeEventListener("keydown",i,{capture:!0})},[s,e])}var SR="DismissableLayer",im="dismissableLayer.update",jR="dismissableLayer.pointerDownOutside",_R="dismissableLayer.focusOutside",b0,t1=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),n1=v.forwardRef((t,e)=>{const{disableOutsidePointerEvents:s=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:d,onDismiss:h,...m}=t,p=v.useContext(t1),[y,x]=v.useState(null),w=y?.ownerDocument??globalThis?.document,[,j]=v.useState({}),T=si(e,B=>x(B)),S=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),E=S.indexOf(_),C=y?S.indexOf(y):-1,A=p.layersWithOutsidePointerEventsDisabled.size>0,k=C>=E,M=ER(B=>{const R=B.target,I=[...p.branches].some(te=>te.contains(R));!k||I||(l?.(B),d?.(B),B.defaultPrevented||h?.())},w),P=kR(B=>{const R=B.target;[...p.branches].some(te=>te.contains(R))||(u?.(B),d?.(B),B.defaultPrevented||h?.())},w);return wR(B=>{C===p.layers.size-1&&(i?.(B),!B.defaultPrevented&&h&&(B.preventDefault(),h()))},w),v.useEffect(()=>{if(y)return s&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(b0=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),w0(),()=>{s&&p.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=b0)}},[y,w,s,p]),v.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),w0())},[y,p]),v.useEffect(()=>{const B=()=>j({});return document.addEventListener(im,B),()=>document.removeEventListener(im,B)},[]),o.jsx(Os.div,{...m,ref:T,style:{pointerEvents:A?k?"auto":"none":void 0,...t.style},onFocusCapture:fa(t.onFocusCapture,P.onFocusCapture),onBlurCapture:fa(t.onBlurCapture,P.onBlurCapture),onPointerDownCapture:fa(t.onPointerDownCapture,M.onPointerDownCapture)})});n1.displayName=SR;var NR="DismissableLayerBranch",TR=v.forwardRef((t,e)=>{const s=v.useContext(t1),i=v.useRef(null),l=si(e,i);return v.useEffect(()=>{const u=i.current;if(u)return s.branches.add(u),()=>{s.branches.delete(u)}},[s.branches]),o.jsx(Os.div,{...t,ref:l})});TR.displayName=NR;function ER(t,e=globalThis?.document){const s=Ho(t),i=v.useRef(!1),l=v.useRef(()=>{});return v.useEffect(()=>{const u=h=>{if(h.target&&!i.current){let m=function(){s1(jR,s,p,{discrete:!0})};const p={originalEvent:h};h.pointerType==="touch"?(e.removeEventListener("click",l.current),l.current=m,e.addEventListener("click",l.current,{once:!0})):m()}else e.removeEventListener("click",l.current);i.current=!1},d=window.setTimeout(()=>{e.addEventListener("pointerdown",u)},0);return()=>{window.clearTimeout(d),e.removeEventListener("pointerdown",u),e.removeEventListener("click",l.current)}},[e,s]),{onPointerDownCapture:()=>i.current=!0}}function kR(t,e=globalThis?.document){const s=Ho(t),i=v.useRef(!1);return v.useEffect(()=>{const l=u=>{u.target&&!i.current&&s1(_R,s,{originalEvent:u},{discrete:!1})};return e.addEventListener("focusin",l),()=>e.removeEventListener("focusin",l)},[e,s]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function w0(){const t=new CustomEvent(im);document.dispatchEvent(t)}function s1(t,e,s,{discrete:i}){const l=s.originalEvent.target,u=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:s});e&&l.addEventListener(t,e,{once:!0}),i?bR(l,u):l.dispatchEvent(u)}var pf="focusScope.autoFocusOnMount",gf="focusScope.autoFocusOnUnmount",S0={bubbles:!1,cancelable:!0},CR="FocusScope",a1=v.forwardRef((t,e)=>{const{loop:s=!1,trapped:i=!1,onMountAutoFocus:l,onUnmountAutoFocus:u,...d}=t,[h,m]=v.useState(null),p=Ho(l),y=Ho(u),x=v.useRef(null),w=si(e,S=>m(S)),j=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(i){let S=function(A){if(j.paused||!h)return;const k=A.target;h.contains(k)?x.current=k:oa(x.current,{select:!0})},_=function(A){if(j.paused||!h)return;const k=A.relatedTarget;k!==null&&(h.contains(k)||oa(x.current,{select:!0}))},E=function(A){if(document.activeElement===document.body)for(const M of A)M.removedNodes.length>0&&oa(h)};document.addEventListener("focusin",S),document.addEventListener("focusout",_);const C=new MutationObserver(E);return h&&C.observe(h,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",_),C.disconnect()}}},[i,h,j.paused]),v.useEffect(()=>{if(h){_0.add(j);const S=document.activeElement;if(!h.contains(S)){const E=new CustomEvent(pf,S0);h.addEventListener(pf,p),h.dispatchEvent(E),E.defaultPrevented||(AR(PR(i1(h)),{select:!0}),document.activeElement===S&&oa(h))}return()=>{h.removeEventListener(pf,p),setTimeout(()=>{const E=new CustomEvent(gf,S0);h.addEventListener(gf,y),h.dispatchEvent(E),E.defaultPrevented||oa(S??document.body,{select:!0}),h.removeEventListener(gf,y),_0.remove(j)},0)}}},[h,p,y,j]);const T=v.useCallback(S=>{if(!s&&!i||j.paused)return;const _=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,E=document.activeElement;if(_&&E){const C=S.currentTarget,[A,k]=RR(C);A&&k?!S.shiftKey&&E===k?(S.preventDefault(),s&&oa(A,{select:!0})):S.shiftKey&&E===A&&(S.preventDefault(),s&&oa(k,{select:!0})):E===C&&S.preventDefault()}},[s,i,j.paused]);return o.jsx(Os.div,{tabIndex:-1,...d,ref:w,onKeyDown:T})});a1.displayName=CR;function AR(t,{select:e=!1}={}){const s=document.activeElement;for(const i of t)if(oa(i,{select:e}),document.activeElement!==s)return}function RR(t){const e=i1(t),s=j0(e,t),i=j0(e.reverse(),t);return[s,i]}function i1(t){const e=[],s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const l=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||l?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)e.push(s.currentNode);return e}function j0(t,e){for(const s of t)if(!OR(s,{upTo:e}))return s}function OR(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function MR(t){return t instanceof HTMLInputElement&&"select"in t}function oa(t,{select:e=!1}={}){if(t&&t.focus){const s=document.activeElement;t.focus({preventScroll:!0}),t!==s&&MR(t)&&e&&t.select()}}var _0=DR();function DR(){let t=[];return{add(e){const s=t[0];e!==s&&s?.pause(),t=N0(t,e),t.unshift(e)},remove(e){t=N0(t,e),t[0]?.resume()}}}function N0(t,e){const s=[...t],i=s.indexOf(e);return i!==-1&&s.splice(i,1),s}function PR(t){return t.filter(e=>e.tagName!=="A")}var zR="Portal",r1=v.forwardRef((t,e)=>{const{container:s,...i}=t,[l,u]=v.useState(!1);qo(()=>u(!0),[]);const d=s||l&&globalThis?.document?.body;return d?VA.createPortal(o.jsx(Os.div,{...i,ref:e}),d):null});r1.displayName=zR;function LR(t,e){return v.useReducer((s,i)=>e[s][i]??s,t)}var Ru=t=>{const{present:e,children:s}=t,i=UR(e),l=typeof s=="function"?s({present:i.isPresent}):v.Children.only(s),u=si(i.ref,BR(l));return typeof s=="function"||i.isPresent?v.cloneElement(l,{ref:u}):null};Ru.displayName="Presence";function UR(t){const[e,s]=v.useState(),i=v.useRef(null),l=v.useRef(t),u=v.useRef("none"),d=t?"mounted":"unmounted",[h,m]=LR(d,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const p=Lc(i.current);u.current=h==="mounted"?p:"none"},[h]),qo(()=>{const p=i.current,y=l.current;if(y!==t){const w=u.current,j=Lc(p);t?m("MOUNT"):j==="none"||p?.display==="none"?m("UNMOUNT"):m(y&&w!==j?"ANIMATION_OUT":"UNMOUNT"),l.current=t}},[t,m]),qo(()=>{if(e){let p;const y=e.ownerDocument.defaultView??window,x=j=>{const S=Lc(i.current).includes(CSS.escape(j.animationName));if(j.target===e&&S&&(m("ANIMATION_END"),!l.current)){const _=e.style.animationFillMode;e.style.animationFillMode="forwards",p=y.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=_)})}},w=j=>{j.target===e&&(u.current=Lc(i.current))};return e.addEventListener("animationstart",w),e.addEventListener("animationcancel",x),e.addEventListener("animationend",x),()=>{y.clearTimeout(p),e.removeEventListener("animationstart",w),e.removeEventListener("animationcancel",x),e.removeEventListener("animationend",x)}}else m("ANIMATION_END")},[e,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:v.useCallback(p=>{i.current=p?getComputedStyle(p):null,s(p)},[])}}function Lc(t){return t?.animationName||"none"}function BR(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning;return s?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning,s?t.props.ref:t.props.ref||t.ref)}var yf=0;function VR(){v.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??T0()),document.body.insertAdjacentElement("beforeend",t[1]??T0()),yf++,()=>{yf===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),yf--}},[])}function T0(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Yc="right-scroll-bar-position",Xc="width-before-scroll-bar",IR="with-scroll-bars-hidden",$R="--removed-body-scroll-bar-size";function vf(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function qR(t,e){var s=v.useState(function(){return{value:t,callback:e,facade:{get current(){return s.value},set current(i){var l=s.value;l!==i&&(s.value=i,s.callback(i,l))}}}})[0];return s.callback=e,s.facade}var HR=typeof window<"u"?v.useLayoutEffect:v.useEffect,E0=new WeakMap;function GR(t,e){var s=qR(null,function(i){return t.forEach(function(l){return vf(l,i)})});return HR(function(){var i=E0.get(s);if(i){var l=new Set(i),u=new Set(t),d=s.current;l.forEach(function(h){u.has(h)||vf(h,null)}),u.forEach(function(h){l.has(h)||vf(h,d)})}E0.set(s,t)},[t]),s}function FR(t){return t}function KR(t,e){e===void 0&&(e=FR);var s=[],i=!1,l={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:t},useMedium:function(u){var d=e(u,i);return s.push(d),function(){s=s.filter(function(h){return h!==d})}},assignSyncMedium:function(u){for(i=!0;s.length;){var d=s;s=[],d.forEach(u)}s={push:function(h){return u(h)},filter:function(){return s}}},assignMedium:function(u){i=!0;var d=[];if(s.length){var h=s;s=[],h.forEach(u),d=s}var m=function(){var y=d;d=[],y.forEach(u)},p=function(){return Promise.resolve().then(m)};p(),s={push:function(y){d.push(y),p()},filter:function(y){return d=d.filter(y),s}}}};return l}function YR(t){t===void 0&&(t={});var e=KR(null);return e.options=ss({async:!0,ssr:!1},t),e}var o1=function(t){var e=t.sideCar,s=gr(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=e.read();if(!i)throw new Error("Sidecar medium not found");return v.createElement(i,ss({},s))};o1.isSideCarExport=!0;function XR(t,e){return t.useMedium(e),o1}var l1=YR(),xf=function(){},Ou=v.forwardRef(function(t,e){var s=v.useRef(null),i=v.useState({onScrollCapture:xf,onWheelCapture:xf,onTouchMoveCapture:xf}),l=i[0],u=i[1],d=t.forwardProps,h=t.children,m=t.className,p=t.removeScrollBar,y=t.enabled,x=t.shards,w=t.sideCar,j=t.noRelative,T=t.noIsolation,S=t.inert,_=t.allowPinchZoom,E=t.as,C=E===void 0?"div":E,A=t.gapMode,k=gr(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),M=w,P=GR([s,e]),B=ss(ss({},k),l);return v.createElement(v.Fragment,null,y&&v.createElement(M,{sideCar:l1,removeScrollBar:p,shards:x,noRelative:j,noIsolation:T,inert:S,setCallbacks:u,allowPinchZoom:!!_,lockRef:s,gapMode:A}),d?v.cloneElement(v.Children.only(h),ss(ss({},B),{ref:P})):v.createElement(C,ss({},B,{className:m,ref:P}),h))});Ou.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ou.classNames={fullWidth:Xc,zeroRight:Yc};var WR=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function JR(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=WR();return e&&t.setAttribute("nonce",e),t}function QR(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function ZR(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var eO=function(){var t=0,e=null;return{add:function(s){t==0&&(e=JR())&&(QR(e,s),ZR(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},tO=function(){var t=eO();return function(e,s){v.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&s])}},c1=function(){var t=tO(),e=function(s){var i=s.styles,l=s.dynamic;return t(i,l),null};return e},nO={left:0,top:0,right:0,gap:0},bf=function(t){return parseInt(t||"",10)||0},sO=function(t){var e=window.getComputedStyle(document.body),s=e[t==="padding"?"paddingLeft":"marginLeft"],i=e[t==="padding"?"paddingTop":"marginTop"],l=e[t==="padding"?"paddingRight":"marginRight"];return[bf(s),bf(i),bf(l)]},aO=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return nO;var e=sO(t),s=document.documentElement.clientWidth,i=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,i-s+e[2]-e[0])}},iO=c1(),cr="data-scroll-locked",rO=function(t,e,s,i){var l=t.left,u=t.top,d=t.right,h=t.gap;return s===void 0&&(s="margin"),`
51
+ `);const P=await k.signMessage(new TextEncoder().encode(T),"utf8");if(!P||!(P instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");S=P}}try{const{data:_,error:E}=await Re(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:T,signature:Ka(S)},!((w=e.options)===null||w===void 0)&&w.captchaToken?{gotrue_meta_security:{captcha_token:(j=e.options)===null||j===void 0?void 0:j.captchaToken}}:null),xform:$n});if(E)throw E;if(!_||!_.session||!_.user){const C=new qi;return this._returnResult({data:{user:null,session:null},error:C})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:E})}catch(_){if(Te(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){const s=await Ua(this.storage,`${this.storageKey}-code-verifier`),[i,l]=(s??"").split("/");try{if(!i&&this.flowType==="pkce")throw new vT;const{data:u,error:d}=await Re(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:i},xform:$n});if(await Ht(this.storage,`${this.storageKey}-code-verifier`),d)throw d;if(!u||!u.session||!u.user){const h=new qi;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:l??null}),error:d})}catch(u){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{const{options:s,provider:i,token:l,access_token:u,nonce:d}=e,h=await Re(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:i,id_token:l,access_token:u,nonce:d,gotrue_meta_security:{captcha_token:s?.captchaToken}},xform:$n}),{data:m,error:p}=h;if(p)return this._returnResult({data:{user:null,session:null},error:p});if(!m||!m.session||!m.user){const y=new qi;return this._returnResult({data:{user:null,session:null},error:y})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:m,error:p})}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOtp(e){var s,i,l,u,d;try{if("email"in e){const{email:h,options:m}=e;let p=null,y=null;this.flowType==="pkce"&&([p,y]=await Hi(this.storage,this.storageKey));const{error:x}=await Re(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:h,data:(s=m?.data)!==null&&s!==void 0?s:{},create_user:(i=m?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:p,code_challenge_method:y},redirectTo:m?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:x})}if("phone"in e){const{phone:h,options:m}=e,{data:p,error:y}=await Re(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:h,data:(l=m?.data)!==null&&l!==void 0?l:{},create_user:(u=m?.shouldCreateUser)!==null&&u!==void 0?u:!0,gotrue_meta_security:{captcha_token:m?.captchaToken},channel:(d=m?.channel)!==null&&d!==void 0?d:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:p?.message_id},error:y})}throw new Cc("You must provide either an email or phone number.")}catch(h){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(h))return this._returnResult({data:{user:null,session:null},error:h});throw h}}async verifyOtp(e){var s,i;try{let l,u;"options"in e&&(l=(s=e.options)===null||s===void 0?void 0:s.redirectTo,u=(i=e.options)===null||i===void 0?void 0:i.captchaToken);const{data:d,error:h}=await Re(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:u}}),redirectTo:l,xform:$n});if(h)throw h;if(!d)throw new Error("An error occurred on token verification.");const m=d.session,p=d.user;return m?.access_token&&(await this._saveSession(m),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(l){if(Te(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async signInWithSSO(e){var s,i,l,u,d;try{let h=null,m=null;this.flowType==="pkce"&&([h,m]=await Hi(this.storage,this.storageKey));const p=await Re(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(i=(s=e.options)===null||s===void 0?void 0:s.redirectTo)!==null&&i!==void 0?i:void 0}),!((l=e?.options)===null||l===void 0)&&l.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:h,code_challenge_method:m}),headers:this.headers,xform:qT});return!((u=p.data)===null||u===void 0)&&u.url&&Gt()&&!(!((d=e.options)===null||d===void 0)&&d.skipBrowserRedirect)&&window.location.assign(p.data.url),this._returnResult(p)}catch(h){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(h))return this._returnResult({data:null,error:h});throw h}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:s},error:i}=e;if(i)throw i;if(!s)throw new xn;const{error:l}=await Re(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return this._returnResult({data:{user:null,session:null},error:l})})}catch(e){if(Te(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const s=`${this.url}/resend`;if("email"in e){const{email:i,type:l,options:u}=e,{error:d}=await Re(this.fetch,"POST",s,{headers:this.headers,body:{email:i,type:l,gotrue_meta_security:{captcha_token:u?.captchaToken}},redirectTo:u?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}else if("phone"in e){const{phone:i,type:l,options:u}=e,{data:d,error:h}=await Re(this.fetch,"POST",s,{headers:this.headers,body:{phone:i,type:l,gotrue_meta_security:{captcha_token:u?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:d?.message_id},error:h})}throw new Cc("You must provide either an email or phone number and a type")}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async s=>s))}async _acquireLock(e,s){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const i=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),l=(async()=>(await i,await s()))();return this.pendingInLock.push((async()=>{try{await l}catch{}})()),l}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const i=s();for(this.pendingInLock.push((async()=>{try{await i}catch{}})()),await i;this.pendingInLock.length;){const l=[...this.pendingInLock];await Promise.all(l),this.pendingInLock.splice(0,l.length)}return await i}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const s=await this.__loadSession();return await e(s)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const s=await Ua(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?e=s:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const i=e.expires_at?e.expires_at*1e3-Date.now()<rf:!1;if(this._debug("#__loadSession()",`session has${i?"":" not"} expired`,"expires_at",e.expires_at),!i){if(this.userStorage){const d=await Ua(this.userStorage,this.storageKey+"-user");d?.user?e.user=d.user:e.user=cf()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const d={value:this.suppressGetSessionWarning};e.user=BT(e.user,d),d.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);return u?this._returnResult({data:{session:null},error:u}):this._returnResult({data:{session:l},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const s=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return s.data.user&&(this.suppressGetSessionWarning=!0),s}async _getUser(e){try{return e?await Re(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ua}):await this._useSession(async s=>{var i,l,u;const{data:d,error:h}=s;if(h)throw h;return!(!((i=d.session)===null||i===void 0)&&i.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new xn}:await Re(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0,xform:ua})})}catch(s){if(Te(s))return of(s)&&(await this._removeSession(),await Ht(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:s});throw s}}async updateUser(e,s={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,s))}async _updateUser(e,s={}){try{return await this._useSession(async i=>{const{data:l,error:u}=i;if(u)throw u;if(!l.session)throw new xn;const d=l.session;let h=null,m=null;this.flowType==="pkce"&&e.email!=null&&([h,m]=await Hi(this.storage,this.storageKey));const{data:p,error:y}=await Re(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:s?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:h,code_challenge_method:m}),jwt:d.access_token,xform:ua});if(y)throw y;return d.user=p.user,await this._saveSession(d),await this._notifyAllSubscribers("USER_UPDATED",d),this._returnResult({data:{user:d.user},error:null})})}catch(i){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(i))return this._returnResult({data:{user:null},error:i});throw i}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new xn;const s=Date.now()/1e3;let i=s,l=!0,u=null;const{payload:d}=Rc(e.access_token);if(d.exp&&(i=d.exp,l=i<=s),l){const{data:h,error:m}=await this._callRefreshToken(e.refresh_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});if(!h)return{data:{user:null,session:null},error:null};u=h}else{const{data:h,error:m}=await this._getUser(e.access_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});u={access_token:e.access_token,refresh_token:e.refresh_token,user:h.user,token_type:"bearer",expires_in:i-s,expires_at:i},await this._saveSession(u),await this._notifyAllSubscribers("SIGNED_IN",u)}return this._returnResult({data:{user:u.user,session:u},error:null})}catch(s){if(Te(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async s=>{var i;if(!e){const{data:d,error:h}=s;if(h)throw h;e=(i=d.session)!==null&&i!==void 0?i:void 0}if(!e?.refresh_token)throw new xn;const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);return u?this._returnResult({data:{user:null,session:null},error:u}):l?this._returnResult({data:{user:l.user,session:l},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(s){if(Te(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async _getSessionFromURL(e,s){try{if(!Gt())throw new Ac("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ac(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(s){case"implicit":if(this.flowType==="pkce")throw new Fx("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ac("Not a valid implicit grant flow url.");break;default:}if(s==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Fx("No code detected.");const{data:C,error:A}=await this._exchangeCodeForSession(e.code);if(A)throw A;const k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:C.session,redirectType:null},error:null}}const{provider_token:i,provider_refresh_token:l,access_token:u,refresh_token:d,expires_in:h,expires_at:m,token_type:p}=e;if(!u||!h||!d||!p)throw new Ac("No session defined in URL");const y=Math.round(Date.now()/1e3),x=parseInt(h);let w=y+x;m&&(w=parseInt(m));const j=w-y;j*1e3<=Qi&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${j}s, should have been closer to ${x}s`);const T=w-x;y-T>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",T,w,y):y-T<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",T,w,y);const{data:S,error:_}=await this._getUser(u);if(_)throw _;const E={provider_token:i,provider_refresh_token:l,access_token:u,expires_in:x,expires_at:w,refresh_token:d,token_type:p,user:S.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:E,redirectType:e.type},error:null})}catch(i){if(Te(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const s=await Ua(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&s)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async s=>{var i;const{data:l,error:u}=s;if(u&&!of(u))return this._returnResult({error:u});const d=(i=l.session)===null||i===void 0?void 0:i.access_token;if(d){const{error:h}=await this.admin.signOut(d,e);if(h&&!(gT(h)&&(h.status===404||h.status===401||h.status===403)||of(h)))return this._returnResult({error:h})}return e!=="others"&&(await this._removeSession(),await Ht(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const s=NT(),i={id:s,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",s),this.stateChangeEmitters.delete(s)}};return this._debug("#onAuthStateChange()","registered callback with id",s),this.stateChangeEmitters.set(s,i),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(s)})))(),{data:{subscription:i}}}async _emitInitialSession(e){return await this._useSession(async s=>{var i,l;try{const{data:{session:u},error:d}=s;if(d)throw d;await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",u)),this._debug("INITIAL_SESSION","callback id",e,"session",u)}catch(u){await((l=this.stateChangeEmitters.get(e))===null||l===void 0?void 0:l.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",u),console.error(u)}})}async resetPasswordForEmail(e,s={}){let i=null,l=null;this.flowType==="pkce"&&([i,l]=await Hi(this.storage,this.storageKey,!0));try{return await Re(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:i,code_challenge_method:l,gotrue_meta_security:{captcha_token:s.captchaToken}},headers:this.headers,redirectTo:s.redirectTo})}catch(u){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(u))return this._returnResult({data:null,error:u});throw u}}async getUserIdentities(){var e;try{const{data:s,error:i}=await this.getUser();if(i)throw i;return this._returnResult({data:{identities:(e=s.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var s;try{const{data:i,error:l}=await this._useSession(async u=>{var d,h,m,p,y;const{data:x,error:w}=u;if(w)throw w;const j=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(d=e.options)===null||d===void 0?void 0:d.redirectTo,scopes:(h=e.options)===null||h===void 0?void 0:h.scopes,queryParams:(m=e.options)===null||m===void 0?void 0:m.queryParams,skipBrowserRedirect:!0});return await Re(this.fetch,"GET",j,{headers:this.headers,jwt:(y=(p=x.session)===null||p===void 0?void 0:p.access_token)!==null&&y!==void 0?y:void 0})});if(l)throw l;return Gt()&&!(!((s=e.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(i?.url),this._returnResult({data:{provider:e.provider,url:i?.url},error:null})}catch(i){if(Te(i))return this._returnResult({data:{provider:e.provider,url:null},error:i});throw i}}async linkIdentityIdToken(e){return await this._useSession(async s=>{var i;try{const{error:l,data:{session:u}}=s;if(l)throw l;const{options:d,provider:h,token:m,access_token:p,nonce:y}=e,x=await Re(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(i=u?.access_token)!==null&&i!==void 0?i:void 0,body:{provider:h,id_token:m,access_token:p,nonce:y,link_identity:!0,gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:$n}),{data:w,error:j}=x;return j?this._returnResult({data:{user:null,session:null},error:j}):!w||!w.session||!w.user?this._returnResult({data:{user:null,session:null},error:new qi}):(w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("USER_UPDATED",w.session)),this._returnResult({data:w,error:j}))}catch(l){if(await Ht(this.storage,`${this.storageKey}-code-verifier`),Te(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}})}async unlinkIdentity(e){try{return await this._useSession(async s=>{var i,l;const{data:u,error:d}=s;if(d)throw d;return await Re(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(l=(i=u.session)===null||i===void 0?void 0:i.access_token)!==null&&l!==void 0?l:void 0})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _refreshAccessToken(e){const s=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{const i=Date.now();return await CT(async l=>(l>0&&await kT(200*Math.pow(2,l-1)),this._debug(s,"refreshing attempt",l),await Re(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:$n})),(l,u)=>{const d=200*Math.pow(2,l);return u&&lf(u)&&Date.now()+d-i<Qi})}catch(i){if(this._debug(s,"error",i),Te(i))return this._returnResult({data:{session:null,user:null},error:i});throw i}finally{this._debug(s,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,s){const i=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:s.redirectTo,scopes:s.scopes,queryParams:s.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",s,"url",i),Gt()&&!s.skipBrowserRedirect&&window.location.assign(i),{data:{provider:e,url:i},error:null}}async _recoverAndRefresh(){var e,s;const i="#_recoverAndRefresh()";this._debug(i,"begin");try{const l=await Ua(this.storage,this.storageKey);if(l&&this.userStorage){let d=await Ua(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!d&&(d={user:l.user},await Zi(this.userStorage,this.storageKey+"-user",d)),l.user=(e=d?.user)!==null&&e!==void 0?e:cf()}else if(l&&!l.user&&!l.user){const d=await Ua(this.storage,this.storageKey+"-user");d&&d?.user?(l.user=d.user,await Ht(this.storage,this.storageKey+"-user"),await Zi(this.storage,this.storageKey,l)):l.user=cf()}if(this._debug(i,"session from storage",l),!this._isValidSession(l)){this._debug(i,"session is not valid"),l!==null&&await this._removeSession();return}const u=((s=l.expires_at)!==null&&s!==void 0?s:1/0)*1e3-Date.now()<rf;if(this._debug(i,`session has${u?"":" not"} expired with margin of ${rf}s`),u){if(this.autoRefreshToken&&l.refresh_token){const{error:d}=await this._callRefreshToken(l.refresh_token);d&&(console.error(d),lf(d)||(this._debug(i,"refresh failed with a non-retryable error, removing the session",d),await this._removeSession()))}}else if(l.user&&l.user.__isUserNotAvailableProxy===!0)try{const{data:d,error:h}=await this._getUser(l.access_token);!h&&d?.user?(l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("SIGNED_IN",l)):this._debug(i,"could not get user data, skipping SIGNED_IN notification")}catch(d){console.error("Error getting user data:",d),this._debug(i,"error getting user data, skipping SIGNED_IN notification",d)}else await this._notifyAllSubscribers("SIGNED_IN",l)}catch(l){this._debug(i,"error",l),console.error(l);return}finally{this._debug(i,"end")}}async _callRefreshToken(e){var s,i;if(!e)throw new xn;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const l=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(l,"begin");try{this.refreshingDeferred=new Nu;const{data:u,error:d}=await this._refreshAccessToken(e);if(d)throw d;if(!u.session)throw new xn;await this._saveSession(u.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",u.session);const h={data:u.session,error:null};return this.refreshingDeferred.resolve(h),h}catch(u){if(this._debug(l,"error",u),Te(u)){const d={data:null,error:u};return lf(u)||await this._removeSession(),(s=this.refreshingDeferred)===null||s===void 0||s.resolve(d),d}throw(i=this.refreshingDeferred)===null||i===void 0||i.reject(u),u}finally{this.refreshingDeferred=null,this._debug(l,"end")}}async _notifyAllSubscribers(e,s,i=!0){const l=`#_notifyAllSubscribers(${e})`;this._debug(l,"begin",s,`broadcast = ${i}`);try{this.broadcastChannel&&i&&this.broadcastChannel.postMessage({event:e,session:s});const u=[],d=Array.from(this.stateChangeEmitters.values()).map(async h=>{try{await h.callback(e,s)}catch(m){u.push(m)}});if(await Promise.all(d),u.length>0){for(let h=0;h<u.length;h+=1)console.error(u[h]);throw u[0]}}finally{this._debug(l,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ht(this.storage,`${this.storageKey}-code-verifier`);const s=Object.assign({},e),i=s.user&&s.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!i&&s.user&&await Zi(this.userStorage,this.storageKey+"-user",{user:s.user});const l=Object.assign({},s);delete l.user;const u=Jx(l);await Zi(this.storage,this.storageKey,u)}else{const l=Jx(s);await Zi(this.storage,this.storageKey,l)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ht(this.storage,this.storageKey),await Ht(this.storage,this.storageKey+"-code-verifier"),await Ht(this.storage,this.storageKey+"-user"),this.userStorage&&await Ht(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Gt()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(s){console.error("removing visibilitychange callback failed",s)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Qi);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const s=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=s,s&&typeof s=="object"&&typeof s.unref=="function"?s.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(s)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const s=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,s&&clearTimeout(s)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async s=>{const{data:{session:i}}=s;if(!i||!i.refresh_token||!i.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const l=Math.floor((i.expires_at*1e3-e)/Qi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${l} ticks, a tick lasts ${Qi}ms, refresh threshold is ${Yf} ticks`),l<=Yf&&await this._callRefreshToken(i.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof pw)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Gt()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const s=`#_onVisibilityChanged(${e})`;this._debug(s,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(s,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,s,i){const l=[`provider=${encodeURIComponent(s)}`];if(i?.redirectTo&&l.push(`redirect_to=${encodeURIComponent(i.redirectTo)}`),i?.scopes&&l.push(`scopes=${encodeURIComponent(i.scopes)}`),this.flowType==="pkce"){const[u,d]=await Hi(this.storage,this.storageKey),h=new URLSearchParams({code_challenge:`${encodeURIComponent(u)}`,code_challenge_method:`${encodeURIComponent(d)}`});l.push(h.toString())}if(i?.queryParams){const u=new URLSearchParams(i.queryParams);l.push(u.toString())}return i?.skipBrowserRedirect&&l.push(`skip_http_redirect=${i.skipBrowserRedirect}`),`${e}?${l.join("&")}`}async _unenroll(e){try{return await this._useSession(async s=>{var i;const{data:l,error:u}=s;return u?this._returnResult({data:null,error:u}):await Re(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(i=l?.session)===null||i===void 0?void 0:i.access_token})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _enroll(e){try{return await this._useSession(async s=>{var i,l;const{data:u,error:d}=s;if(d)return this._returnResult({data:null,error:d});const h=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:m,error:p}=await Re(this.fetch,"POST",`${this.url}/factors`,{body:h,headers:this.headers,jwt:(i=u?.session)===null||i===void 0?void 0:i.access_token});return p?this._returnResult({data:null,error:p}):(e.factorType==="totp"&&m.type==="totp"&&(!((l=m?.totp)===null||l===void 0)&&l.qr_code)&&(m.totp.qr_code=`data:image/svg+xml;utf-8,${m.totp.qr_code}`),this._returnResult({data:m,error:null}))})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async s=>{var i;const{data:l,error:u}=s;if(u)return this._returnResult({data:null,error:u});const d=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?aE(e.webauthn.credential_response):iE(e.webauthn.credential_response)})}:{code:e.code}),{data:h,error:m}=await Re(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:d,headers:this.headers,jwt:(i=l?.session)===null||i===void 0?void 0:i.access_token});return m?this._returnResult({data:null,error:m}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+h.expires_in},h)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",h),this._returnResult({data:h,error:m}))})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async s=>{var i;const{data:l,error:u}=s;if(u)return this._returnResult({data:null,error:u});const d=await Re(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(i=l?.session)===null||i===void 0?void 0:i.access_token});if(d.error)return d;const{data:h}=d;if(h.type!=="webauthn")return{data:h,error:null};switch(h.webauthn.type){case"create":return{data:Object.assign(Object.assign({},h),{webauthn:Object.assign(Object.assign({},h.webauthn),{credential_options:Object.assign(Object.assign({},h.webauthn.credential_options),{publicKey:nE(h.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},h),{webauthn:Object.assign(Object.assign({},h.webauthn),{credential_options:Object.assign(Object.assign({},h.webauthn.credential_options),{publicKey:sE(h.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}})}async _challengeAndVerify(e){const{data:s,error:i}=await this._challenge({factorId:e.factorId});return i?this._returnResult({data:null,error:i}):await this._verify({factorId:e.factorId,challengeId:s.id,code:e.code})}async _listFactors(){var e;const{data:{user:s},error:i}=await this.getUser();if(i)return{data:null,error:i};const l={all:[],phone:[],totp:[],webauthn:[]};for(const u of(e=s?.factors)!==null&&e!==void 0?e:[])l.all.push(u),u.status==="verified"&&l[u.factor_type].push(u);return{data:l,error:null}}async _getAuthenticatorAssuranceLevel(e){var s,i,l,u;if(e)try{const{payload:j}=Rc(e);let T=null;j.aal&&(T=j.aal);let S=T;const{data:{user:_},error:E}=await this.getUser(e);if(E)return this._returnResult({data:null,error:E});((i=(s=_?.factors)===null||s===void 0?void 0:s.filter(k=>k.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(S="aal2");const A=j.amr||[];return{data:{currentLevel:T,nextLevel:S,currentAuthenticationMethods:A},error:null}}catch(j){if(Te(j))return this._returnResult({data:null,error:j});throw j}const{data:{session:d},error:h}=await this.getSession();if(h)return this._returnResult({data:null,error:h});if(!d)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:m}=Rc(d.access_token);let p=null;m.aal&&(p=m.aal);let y=p;((u=(l=d.user.factors)===null||l===void 0?void 0:l.filter(j=>j.status==="verified"))!==null&&u!==void 0?u:[]).length>0&&(y="aal2");const w=m.amr||[];return{data:{currentLevel:p,nextLevel:y,currentAuthenticationMethods:w},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async s=>{const{data:{session:i},error:l}=s;return l?this._returnResult({data:null,error:l}):i?await Re(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:i.access_token,xform:u=>({data:u,error:null})}):this._returnResult({data:null,error:new xn})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async _approveAuthorization(e,s){try{return await this._useSession(async i=>{const{data:{session:l},error:u}=i;if(u)return this._returnResult({data:null,error:u});if(!l)return this._returnResult({data:null,error:new xn});const d=await Re(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"approve"},xform:h=>({data:h,error:null})});return d.data&&d.data.redirect_url&&Gt()&&!s?.skipBrowserRedirect&&window.location.assign(d.data.redirect_url),d})}catch(i){if(Te(i))return this._returnResult({data:null,error:i});throw i}}async _denyAuthorization(e,s){try{return await this._useSession(async i=>{const{data:{session:l},error:u}=i;if(u)return this._returnResult({data:null,error:u});if(!l)return this._returnResult({data:null,error:new xn});const d=await Re(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"deny"},xform:h=>({data:h,error:null})});return d.data&&d.data.redirect_url&&Gt()&&!s?.skipBrowserRedirect&&window.location.assign(d.data.redirect_url),d})}catch(i){if(Te(i))return this._returnResult({data:null,error:i});throw i}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:s},error:i}=e;return i?this._returnResult({data:null,error:i}):s?await Re(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,xform:l=>({data:l,error:null})}):this._returnResult({data:null,error:new xn})})}catch(e){if(Te(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async s=>{const{data:{session:i},error:l}=s;return l?this._returnResult({data:null,error:l}):i?(await Re(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:i.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new xn})})}catch(s){if(Te(s))return this._returnResult({data:null,error:s});throw s}}async fetchJwk(e,s={keys:[]}){let i=s.keys.find(h=>h.kid===e);if(i)return i;const l=Date.now();if(i=this.jwks.keys.find(h=>h.kid===e),i&&this.jwks_cached_at+mT>l)return i;const{data:u,error:d}=await Re(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(d)throw d;return!u.keys||u.keys.length===0||(this.jwks=u,this.jwks_cached_at=l,i=u.keys.find(h=>h.kid===e),!i)?null:i}async getClaims(e,s={}){try{let i=e;if(!i){const{data:j,error:T}=await this.getSession();if(T||!j.session)return this._returnResult({data:null,error:T});i=j.session.access_token}const{header:l,payload:u,signature:d,raw:{header:h,payload:m}}=Rc(i);s?.allowExpired||zT(u.exp);const p=!l.alg||l.alg.startsWith("HS")||!l.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(l.kid,s?.keys?{keys:s.keys}:s?.jwks);if(!p){const{error:j}=await this.getUser(i);if(j)throw j;return{data:{claims:u,header:l,signature:d},error:null}}const y=LT(l.alg),x=await crypto.subtle.importKey("jwk",p,y,!0,["verify"]);if(!await crypto.subtle.verify(y,x,d,jT(`${h}.${m}`)))throw new Jf("Invalid JWT signature");return{data:{claims:u,header:l,signature:d},error:null}}catch(i){if(Te(i))return this._returnResult({data:null,error:i});throw i}}}Lo.nextInstanceID={};const mE=Lo,pE="2.97.0";let wo="";typeof Deno<"u"?wo="deno":typeof document<"u"?wo="web":typeof navigator<"u"&&navigator.product==="ReactNative"?wo="react-native":wo="node";const gE={"X-Client-Info":`supabase-js-${wo}/${pE}`},yE={headers:gE},vE={schema:"public"},xE={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bE={};function Uo(t){"@babel/helpers - typeof";return Uo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Uo(t)}function wE(t,e){if(Uo(t)!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var i=s.call(t,e);if(Uo(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function SE(t){var e=wE(t,"string");return Uo(e)=="symbol"?e:e+""}function jE(t,e,s){return(e=SE(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function i0(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),s.push.apply(s,i)}return s}function yt(t){for(var e=1;e<arguments.length;e++){var s=arguments[e]!=null?arguments[e]:{};e%2?i0(Object(s),!0).forEach(function(i){jE(t,i,s[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):i0(Object(s)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(s,i))})}return t}const _E=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),NE=()=>Headers,TE=(t,e,s)=>{const i=_E(s),l=NE();return async(u,d)=>{var h;const m=(h=await e())!==null&&h!==void 0?h:t;let p=new l(d?.headers);return p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${m}`),i(u,yt(yt({},d),{},{headers:p}))}};function EE(t){return t.endsWith("/")?t:t+"/"}function kE(t,e){var s,i;const{db:l,auth:u,realtime:d,global:h}=t,{db:m,auth:p,realtime:y,global:x}=e,w={db:yt(yt({},m),l),auth:yt(yt({},p),u),realtime:yt(yt({},y),d),storage:{},global:yt(yt(yt({},x),h),{},{headers:yt(yt({},(s=x?.headers)!==null&&s!==void 0?s:{}),(i=h?.headers)!==null&&i!==void 0?i:{})}),accessToken:async()=>""};return t.accessToken?w.accessToken=t.accessToken:delete w.accessToken,w}function CE(t){const e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(EE(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var AE=class extends mE{constructor(t){super(t)}},RE=class{constructor(t,e,s){var i,l;this.supabaseUrl=t,this.supabaseKey=e;const u=CE(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",u),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",u),this.storageUrl=new URL("storage/v1",u),this.functionsUrl=new URL("functions/v1",u);const d=`sb-${u.hostname.split(".")[0]}-auth-token`,h={db:vE,realtime:bE,auth:yt(yt({},xE),{},{storageKey:d}),global:yE},m=kE(s??{},h);if(this.storageKey=(i=m.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(l=m.global.headers)!==null&&l!==void 0?l:{},m.accessToken)this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(y,x)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(x)} is not possible`)}});else{var p;this.auth=this._initSupabaseAuthClient((p=m.auth)!==null&&p!==void 0?p:{},this.headers,m.global.fetch)}this.fetch=TE(e,this._getAccessToken.bind(this),m.global.fetch),this.realtime=this._initRealtimeClient(yt({headers:this.headers,accessToken:this._getAccessToken.bind(this)},m.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(y=>this.realtime.setAuth(y)).catch(y=>console.warn("Failed to set initial Realtime auth token:",y)),this.rest=new g2(new URL("rest/v1",u).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch,timeout:m.db.timeout,urlLengthLimit:m.db.urlLengthLimit}),this.storage=new cT(this.storageUrl.href,this.headers,this.fetch,s?.storage),m.accessToken||this._listenForAuthEvents()}get functions(){return new l2(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},s={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,s)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,s;if(t.accessToken)return await t.accessToken();const{data:i}=await t.auth.getSession();return(e=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:s,storage:i,userStorage:l,storageKey:u,flowType:d,lock:h,debug:m,throwOnError:p},y,x){const w={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new AE({url:this.authUrl.href,headers:yt(yt({},w),y),storageKey:u,autoRefreshToken:t,persistSession:e,detectSessionInUrl:s,storage:i,userStorage:l,flowType:d,lock:h,debug:m,throwOnError:p,fetch:x,hasCustomAuthorizationHeader:Object.keys(this.headers).some(j=>j.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new M2(this.realtimeUrl.href,yt(yt({},t),{},{params:yt(yt({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,s){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==s?(this.changedAccessToken=s,this.realtime.setAuth(s)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const zm=(t,e,s)=>new RE(t,e,s);function OE(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const s=e.match(/^v(\d+)\./);return s?parseInt(s[1],10)<=18:!1}OE()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function vw(t){var e,s,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var l=t.length;for(e=0;e<l;e++)t[e]&&(s=vw(t[e]))&&(i&&(i+=" "),i+=s)}else for(s in t)t[s]&&(i&&(i+=" "),i+=s);return i}function xw(){for(var t,e,s=0,i="",l=arguments.length;s<l;s++)(t=arguments[s])&&(e=vw(t))&&(i&&(i+=" "),i+=e);return i}const ME=(t,e)=>{const s=new Array(t.length+e.length);for(let i=0;i<t.length;i++)s[i]=t[i];for(let i=0;i<e.length;i++)s[t.length+i]=e[i];return s},DE=(t,e)=>({classGroupId:t,validator:e}),bw=(t=new Map,e=null,s)=>({nextPart:t,validators:e,classGroupId:s}),ru="-",r0=[],PE="arbitrary..",zE=t=>{const e=UE(t),{conflictingClassGroups:s,conflictingClassGroupModifiers:i}=t;return{getClassGroupId:d=>{if(d.startsWith("[")&&d.endsWith("]"))return LE(d);const h=d.split(ru),m=h[0]===""&&h.length>1?1:0;return ww(h,m,e)},getConflictingClassGroupIds:(d,h)=>{if(h){const m=i[d],p=s[d];return m?p?ME(p,m):m:p||r0}return s[d]||r0}}},ww=(t,e,s)=>{if(t.length-e===0)return s.classGroupId;const l=t[e],u=s.nextPart.get(l);if(u){const p=ww(t,e+1,u);if(p)return p}const d=s.validators;if(d===null)return;const h=e===0?t.join(ru):t.slice(e).join(ru),m=d.length;for(let p=0;p<m;p++){const y=d[p];if(y.validator(h))return y.classGroupId}},LE=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),s=e.indexOf(":"),i=e.slice(0,s);return i?PE+i:void 0})(),UE=t=>{const{theme:e,classGroups:s}=t;return BE(s,e)},BE=(t,e)=>{const s=bw();for(const i in t){const l=t[i];Lm(l,s,i,e)}return s},Lm=(t,e,s,i)=>{const l=t.length;for(let u=0;u<l;u++){const d=t[u];VE(d,e,s,i)}},VE=(t,e,s,i)=>{if(typeof t=="string"){IE(t,e,s);return}if(typeof t=="function"){$E(t,e,s,i);return}qE(t,e,s,i)},IE=(t,e,s)=>{const i=t===""?e:Sw(e,t);i.classGroupId=s},$E=(t,e,s,i)=>{if(HE(t)){Lm(t(i),e,s,i);return}e.validators===null&&(e.validators=[]),e.validators.push(DE(s,t))},qE=(t,e,s,i)=>{const l=Object.entries(t),u=l.length;for(let d=0;d<u;d++){const[h,m]=l[d];Lm(m,Sw(e,h),s,i)}},Sw=(t,e)=>{let s=t;const i=e.split(ru),l=i.length;for(let u=0;u<l;u++){const d=i[u];let h=s.nextPart.get(d);h||(h=bw(),s.nextPart.set(d,h)),s=h}return s},HE=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,GE=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,s=Object.create(null),i=Object.create(null);const l=(u,d)=>{s[u]=d,e++,e>t&&(e=0,i=s,s=Object.create(null))};return{get(u){let d=s[u];if(d!==void 0)return d;if((d=i[u])!==void 0)return l(u,d),d},set(u,d){u in s?s[u]=d:l(u,d)}}},Qf="!",o0=":",FE=[],l0=(t,e,s,i,l)=>({modifiers:t,hasImportantModifier:e,baseClassName:s,maybePostfixModifierPosition:i,isExternal:l}),KE=t=>{const{prefix:e,experimentalParseClassName:s}=t;let i=l=>{const u=[];let d=0,h=0,m=0,p;const y=l.length;for(let S=0;S<y;S++){const _=l[S];if(d===0&&h===0){if(_===o0){u.push(l.slice(m,S)),m=S+1;continue}if(_==="/"){p=S;continue}}_==="["?d++:_==="]"?d--:_==="("?h++:_===")"&&h--}const x=u.length===0?l:l.slice(m);let w=x,j=!1;x.endsWith(Qf)?(w=x.slice(0,-1),j=!0):x.startsWith(Qf)&&(w=x.slice(1),j=!0);const T=p&&p>m?p-m:void 0;return l0(u,j,w,T)};if(e){const l=e+o0,u=i;i=d=>d.startsWith(l)?u(d.slice(l.length)):l0(FE,!1,d,void 0,!0)}if(s){const l=i;i=u=>s({className:u,parseClassName:l})}return i},YE=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((s,i)=>{e.set(s,1e6+i)}),s=>{const i=[];let l=[];for(let u=0;u<s.length;u++){const d=s[u],h=d[0]==="[",m=e.has(d);h||m?(l.length>0&&(l.sort(),i.push(...l),l=[]),i.push(d)):l.push(d)}return l.length>0&&(l.sort(),i.push(...l)),i}},XE=t=>({cache:GE(t.cacheSize),parseClassName:KE(t),sortModifiers:YE(t),...zE(t)}),WE=/\s+/,JE=(t,e)=>{const{parseClassName:s,getClassGroupId:i,getConflictingClassGroupIds:l,sortModifiers:u}=e,d=[],h=t.trim().split(WE);let m="";for(let p=h.length-1;p>=0;p-=1){const y=h[p],{isExternal:x,modifiers:w,hasImportantModifier:j,baseClassName:T,maybePostfixModifierPosition:S}=s(y);if(x){m=y+(m.length>0?" "+m:m);continue}let _=!!S,E=i(_?T.substring(0,S):T);if(!E){if(!_){m=y+(m.length>0?" "+m:m);continue}if(E=i(T),!E){m=y+(m.length>0?" "+m:m);continue}_=!1}const C=w.length===0?"":w.length===1?w[0]:u(w).join(":"),A=j?C+Qf:C,k=A+E;if(d.indexOf(k)>-1)continue;d.push(k);const M=l(E,_);for(let P=0;P<M.length;++P){const B=M[P];d.push(A+B)}m=y+(m.length>0?" "+m:m)}return m},QE=(...t)=>{let e=0,s,i,l="";for(;e<t.length;)(s=t[e++])&&(i=jw(s))&&(l&&(l+=" "),l+=i);return l},jw=t=>{if(typeof t=="string")return t;let e,s="";for(let i=0;i<t.length;i++)t[i]&&(e=jw(t[i]))&&(s&&(s+=" "),s+=e);return s},ZE=(t,...e)=>{let s,i,l,u;const d=m=>{const p=e.reduce((y,x)=>x(y),t());return s=XE(p),i=s.cache.get,l=s.cache.set,u=h,h(m)},h=m=>{const p=i(m);if(p)return p;const y=JE(m,s);return l(m,y),y};return u=d,(...m)=>u(QE(...m))},ek=[],At=t=>{const e=s=>s[t]||ek;return e.isThemeGetter=!0,e},_w=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Nw=/^\((?:(\w[\w-]*):)?(.+)\)$/i,tk=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,nk=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,sk=/\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$/,ak=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ik=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,rk=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,aa=t=>tk.test(t),Ue=t=>!!t&&!Number.isNaN(Number(t)),ia=t=>!!t&&Number.isInteger(Number(t)),df=t=>t.endsWith("%")&&Ue(t.slice(0,-1)),Es=t=>nk.test(t),Tw=()=>!0,ok=t=>sk.test(t)&&!ak.test(t),Um=()=>!1,lk=t=>ik.test(t),ck=t=>rk.test(t),uk=t=>!be(t)&&!Se(t),dk=t=>ga(t,Cw,Um),be=t=>_w.test(t),Ba=t=>ga(t,Aw,ok),c0=t=>ga(t,xk,Ue),hk=t=>ga(t,Ow,Tw),fk=t=>ga(t,Rw,Um),u0=t=>ga(t,Ew,Um),mk=t=>ga(t,kw,ck),Oc=t=>ga(t,Mw,lk),Se=t=>Nw.test(t),xo=t=>ni(t,Aw),pk=t=>ni(t,Rw),d0=t=>ni(t,Ew),gk=t=>ni(t,Cw),yk=t=>ni(t,kw),Mc=t=>ni(t,Mw,!0),vk=t=>ni(t,Ow,!0),ga=(t,e,s)=>{const i=_w.exec(t);return i?i[1]?e(i[1]):s(i[2]):!1},ni=(t,e,s=!1)=>{const i=Nw.exec(t);return i?i[1]?e(i[1]):s:!1},Ew=t=>t==="position"||t==="percentage",kw=t=>t==="image"||t==="url",Cw=t=>t==="length"||t==="size"||t==="bg-size",Aw=t=>t==="length",xk=t=>t==="number",Rw=t=>t==="family-name",Ow=t=>t==="number"||t==="weight",Mw=t=>t==="shadow",bk=()=>{const t=At("color"),e=At("font"),s=At("text"),i=At("font-weight"),l=At("tracking"),u=At("leading"),d=At("breakpoint"),h=At("container"),m=At("spacing"),p=At("radius"),y=At("shadow"),x=At("inset-shadow"),w=At("text-shadow"),j=At("drop-shadow"),T=At("blur"),S=At("perspective"),_=At("aspect"),E=At("ease"),C=At("animate"),A=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],M=()=>[...k(),Se,be],P=()=>["auto","hidden","clip","visible","scroll"],B=()=>["auto","contain","none"],R=()=>[Se,be,m],I=()=>[aa,"full","auto",...R()],te=()=>[ia,"none","subgrid",Se,be],ie=()=>["auto",{span:["full",ia,Se,be]},ia,Se,be],fe=()=>[ia,"auto",Se,be],Ne=()=>["auto","min","max","fr",Se,be],ye=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],se=()=>["start","end","center","stretch","center-safe","end-safe"],V=()=>["auto",...R()],F=()=>[aa,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...R()],J=()=>[aa,"screen","full","dvw","lvw","svw","min","max","fit",...R()],ge=()=>[aa,"screen","full","lh","dvh","lvh","svh","min","max","fit",...R()],ne=()=>[t,Se,be],D=()=>[...k(),d0,u0,{position:[Se,be]}],L=()=>["no-repeat",{repeat:["","x","y","space","round"]}],W=()=>["auto","cover","contain",gk,dk,{size:[Se,be]}],ee=()=>[df,xo,Ba],le=()=>["","none","full",p,Se,be],de=()=>["",Ue,xo,Ba],q=()=>["solid","dashed","dotted","double"],pe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],oe=()=>[Ue,df,d0,u0],ze=()=>["","none",T,Se,be],Be=()=>["none",Ue,Se,be],kt=()=>["none",Ue,Se,be],et=()=>[Ue,Se,be],ce=()=>[aa,"full",...R()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Es],breakpoint:[Es],color:[Tw],container:[Es],"drop-shadow":[Es],ease:["in","out","in-out"],font:[uk],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Es],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Es],shadow:[Es],spacing:["px",Ue],text:[Es],"text-shadow":[Es],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",aa,be,Se,_]}],container:["container"],columns:[{columns:[Ue,be,Se,h]}],"break-after":[{"break-after":A()}],"break-before":[{"break-before":A()}],"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"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:M()}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:I()}],"inset-x":[{"inset-x":I()}],"inset-y":[{"inset-y":I()}],start:[{"inset-s":I(),start:I()}],end:[{"inset-e":I(),end:I()}],"inset-bs":[{"inset-bs":I()}],"inset-be":[{"inset-be":I()}],top:[{top:I()}],right:[{right:I()}],bottom:[{bottom:I()}],left:[{left:I()}],visibility:["visible","invisible","collapse"],z:[{z:[ia,"auto",Se,be]}],basis:[{basis:[aa,"full","auto",h,...R()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ue,aa,"auto","initial","none",be]}],grow:[{grow:["",Ue,Se,be]}],shrink:[{shrink:["",Ue,Se,be]}],order:[{order:[ia,"first","last","none",Se,be]}],"grid-cols":[{"grid-cols":te()}],"col-start-end":[{col:ie()}],"col-start":[{"col-start":fe()}],"col-end":[{"col-end":fe()}],"grid-rows":[{"grid-rows":te()}],"row-start-end":[{row:ie()}],"row-start":[{"row-start":fe()}],"row-end":[{"row-end":fe()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":Ne()}],"auto-rows":[{"auto-rows":Ne()}],gap:[{gap:R()}],"gap-x":[{"gap-x":R()}],"gap-y":[{"gap-y":R()}],"justify-content":[{justify:[...ye(),"normal"]}],"justify-items":[{"justify-items":[...se(),"normal"]}],"justify-self":[{"justify-self":["auto",...se()]}],"align-content":[{content:["normal",...ye()]}],"align-items":[{items:[...se(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...se(),{baseline:["","last"]}]}],"place-content":[{"place-content":ye()}],"place-items":[{"place-items":[...se(),"baseline"]}],"place-self":[{"place-self":["auto",...se()]}],p:[{p:R()}],px:[{px:R()}],py:[{py:R()}],ps:[{ps:R()}],pe:[{pe:R()}],pbs:[{pbs:R()}],pbe:[{pbe:R()}],pt:[{pt:R()}],pr:[{pr:R()}],pb:[{pb:R()}],pl:[{pl:R()}],m:[{m:V()}],mx:[{mx:V()}],my:[{my:V()}],ms:[{ms:V()}],me:[{me:V()}],mbs:[{mbs:V()}],mbe:[{mbe:V()}],mt:[{mt:V()}],mr:[{mr:V()}],mb:[{mb:V()}],ml:[{ml:V()}],"space-x":[{"space-x":R()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":R()}],"space-y-reverse":["space-y-reverse"],size:[{size:F()}],"inline-size":[{inline:["auto",...J()]}],"min-inline-size":[{"min-inline":["auto",...J()]}],"max-inline-size":[{"max-inline":["none",...J()]}],"block-size":[{block:["auto",...ge()]}],"min-block-size":[{"min-block":["auto",...ge()]}],"max-block-size":[{"max-block":["none",...ge()]}],w:[{w:[h,"screen",...F()]}],"min-w":[{"min-w":[h,"screen","none",...F()]}],"max-w":[{"max-w":[h,"screen","none","prose",{screen:[d]},...F()]}],h:[{h:["screen","lh",...F()]}],"min-h":[{"min-h":["screen","lh","none",...F()]}],"max-h":[{"max-h":["screen","lh",...F()]}],"font-size":[{text:["base",s,xo,Ba]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,vk,hk]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",df,be]}],"font-family":[{font:[pk,fk,e]}],"font-features":[{"font-features":[be]}],"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:[l,Se,be]}],"line-clamp":[{"line-clamp":[Ue,"none",Se,c0]}],leading:[{leading:[u,...R()]}],"list-image":[{"list-image":["none",Se,be]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Se,be]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:ne()}],"text-color":[{text:ne()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...q(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ue,"from-font","auto",Se,Ba]}],"text-decoration-color":[{decoration:ne()}],"underline-offset":[{"underline-offset":[Ue,"auto",Se,be]}],"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",Se,be]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Se,be]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:D()}],"bg-repeat":[{bg:L()}],"bg-size":[{bg:W()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ia,Se,be],radial:["",Se,be],conic:[ia,Se,be]},yk,mk]}],"bg-color":[{bg:ne()}],"gradient-from-pos":[{from:ee()}],"gradient-via-pos":[{via:ee()}],"gradient-to-pos":[{to:ee()}],"gradient-from":[{from:ne()}],"gradient-via":[{via:ne()}],"gradient-to":[{to:ne()}],rounded:[{rounded:le()}],"rounded-s":[{"rounded-s":le()}],"rounded-e":[{"rounded-e":le()}],"rounded-t":[{"rounded-t":le()}],"rounded-r":[{"rounded-r":le()}],"rounded-b":[{"rounded-b":le()}],"rounded-l":[{"rounded-l":le()}],"rounded-ss":[{"rounded-ss":le()}],"rounded-se":[{"rounded-se":le()}],"rounded-ee":[{"rounded-ee":le()}],"rounded-es":[{"rounded-es":le()}],"rounded-tl":[{"rounded-tl":le()}],"rounded-tr":[{"rounded-tr":le()}],"rounded-br":[{"rounded-br":le()}],"rounded-bl":[{"rounded-bl":le()}],"border-w":[{border:de()}],"border-w-x":[{"border-x":de()}],"border-w-y":[{"border-y":de()}],"border-w-s":[{"border-s":de()}],"border-w-e":[{"border-e":de()}],"border-w-bs":[{"border-bs":de()}],"border-w-be":[{"border-be":de()}],"border-w-t":[{"border-t":de()}],"border-w-r":[{"border-r":de()}],"border-w-b":[{"border-b":de()}],"border-w-l":[{"border-l":de()}],"divide-x":[{"divide-x":de()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":de()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...q(),"hidden","none"]}],"divide-style":[{divide:[...q(),"hidden","none"]}],"border-color":[{border:ne()}],"border-color-x":[{"border-x":ne()}],"border-color-y":[{"border-y":ne()}],"border-color-s":[{"border-s":ne()}],"border-color-e":[{"border-e":ne()}],"border-color-bs":[{"border-bs":ne()}],"border-color-be":[{"border-be":ne()}],"border-color-t":[{"border-t":ne()}],"border-color-r":[{"border-r":ne()}],"border-color-b":[{"border-b":ne()}],"border-color-l":[{"border-l":ne()}],"divide-color":[{divide:ne()}],"outline-style":[{outline:[...q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ue,Se,be]}],"outline-w":[{outline:["",Ue,xo,Ba]}],"outline-color":[{outline:ne()}],shadow:[{shadow:["","none",y,Mc,Oc]}],"shadow-color":[{shadow:ne()}],"inset-shadow":[{"inset-shadow":["none",x,Mc,Oc]}],"inset-shadow-color":[{"inset-shadow":ne()}],"ring-w":[{ring:de()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:ne()}],"ring-offset-w":[{"ring-offset":[Ue,Ba]}],"ring-offset-color":[{"ring-offset":ne()}],"inset-ring-w":[{"inset-ring":de()}],"inset-ring-color":[{"inset-ring":ne()}],"text-shadow":[{"text-shadow":["none",w,Mc,Oc]}],"text-shadow-color":[{"text-shadow":ne()}],opacity:[{opacity:[Ue,Se,be]}],"mix-blend":[{"mix-blend":[...pe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":pe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ue]}],"mask-image-linear-from-pos":[{"mask-linear-from":oe()}],"mask-image-linear-to-pos":[{"mask-linear-to":oe()}],"mask-image-linear-from-color":[{"mask-linear-from":ne()}],"mask-image-linear-to-color":[{"mask-linear-to":ne()}],"mask-image-t-from-pos":[{"mask-t-from":oe()}],"mask-image-t-to-pos":[{"mask-t-to":oe()}],"mask-image-t-from-color":[{"mask-t-from":ne()}],"mask-image-t-to-color":[{"mask-t-to":ne()}],"mask-image-r-from-pos":[{"mask-r-from":oe()}],"mask-image-r-to-pos":[{"mask-r-to":oe()}],"mask-image-r-from-color":[{"mask-r-from":ne()}],"mask-image-r-to-color":[{"mask-r-to":ne()}],"mask-image-b-from-pos":[{"mask-b-from":oe()}],"mask-image-b-to-pos":[{"mask-b-to":oe()}],"mask-image-b-from-color":[{"mask-b-from":ne()}],"mask-image-b-to-color":[{"mask-b-to":ne()}],"mask-image-l-from-pos":[{"mask-l-from":oe()}],"mask-image-l-to-pos":[{"mask-l-to":oe()}],"mask-image-l-from-color":[{"mask-l-from":ne()}],"mask-image-l-to-color":[{"mask-l-to":ne()}],"mask-image-x-from-pos":[{"mask-x-from":oe()}],"mask-image-x-to-pos":[{"mask-x-to":oe()}],"mask-image-x-from-color":[{"mask-x-from":ne()}],"mask-image-x-to-color":[{"mask-x-to":ne()}],"mask-image-y-from-pos":[{"mask-y-from":oe()}],"mask-image-y-to-pos":[{"mask-y-to":oe()}],"mask-image-y-from-color":[{"mask-y-from":ne()}],"mask-image-y-to-color":[{"mask-y-to":ne()}],"mask-image-radial":[{"mask-radial":[Se,be]}],"mask-image-radial-from-pos":[{"mask-radial-from":oe()}],"mask-image-radial-to-pos":[{"mask-radial-to":oe()}],"mask-image-radial-from-color":[{"mask-radial-from":ne()}],"mask-image-radial-to-color":[{"mask-radial-to":ne()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Ue]}],"mask-image-conic-from-pos":[{"mask-conic-from":oe()}],"mask-image-conic-to-pos":[{"mask-conic-to":oe()}],"mask-image-conic-from-color":[{"mask-conic-from":ne()}],"mask-image-conic-to-color":[{"mask-conic-to":ne()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:D()}],"mask-repeat":[{mask:L()}],"mask-size":[{mask:W()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Se,be]}],filter:[{filter:["","none",Se,be]}],blur:[{blur:ze()}],brightness:[{brightness:[Ue,Se,be]}],contrast:[{contrast:[Ue,Se,be]}],"drop-shadow":[{"drop-shadow":["","none",j,Mc,Oc]}],"drop-shadow-color":[{"drop-shadow":ne()}],grayscale:[{grayscale:["",Ue,Se,be]}],"hue-rotate":[{"hue-rotate":[Ue,Se,be]}],invert:[{invert:["",Ue,Se,be]}],saturate:[{saturate:[Ue,Se,be]}],sepia:[{sepia:["",Ue,Se,be]}],"backdrop-filter":[{"backdrop-filter":["","none",Se,be]}],"backdrop-blur":[{"backdrop-blur":ze()}],"backdrop-brightness":[{"backdrop-brightness":[Ue,Se,be]}],"backdrop-contrast":[{"backdrop-contrast":[Ue,Se,be]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ue,Se,be]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ue,Se,be]}],"backdrop-invert":[{"backdrop-invert":["",Ue,Se,be]}],"backdrop-opacity":[{"backdrop-opacity":[Ue,Se,be]}],"backdrop-saturate":[{"backdrop-saturate":[Ue,Se,be]}],"backdrop-sepia":[{"backdrop-sepia":["",Ue,Se,be]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":R()}],"border-spacing-x":[{"border-spacing-x":R()}],"border-spacing-y":[{"border-spacing-y":R()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Se,be]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ue,"initial",Se,be]}],ease:[{ease:["linear","initial",E,Se,be]}],delay:[{delay:[Ue,Se,be]}],animate:[{animate:["none",C,Se,be]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Se,be]}],"perspective-origin":[{"perspective-origin":M()}],rotate:[{rotate:Be()}],"rotate-x":[{"rotate-x":Be()}],"rotate-y":[{"rotate-y":Be()}],"rotate-z":[{"rotate-z":Be()}],scale:[{scale:kt()}],"scale-x":[{"scale-x":kt()}],"scale-y":[{"scale-y":kt()}],"scale-z":[{"scale-z":kt()}],"scale-3d":["scale-3d"],skew:[{skew:et()}],"skew-x":[{"skew-x":et()}],"skew-y":[{"skew-y":et()}],transform:[{transform:[Se,be,"","none","gpu","cpu"]}],"transform-origin":[{origin:M()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ce()}],"translate-x":[{"translate-x":ce()}],"translate-y":[{"translate-y":ce()}],"translate-z":[{"translate-z":ce()}],"translate-none":["translate-none"],accent:[{accent:ne()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:ne()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],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",Se,be]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],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-mbs":[{"scroll-mbs":R()}],"scroll-mbe":[{"scroll-mbe":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-pbs":[{"scroll-pbs":R()}],"scroll-pbe":[{"scroll-pbe":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",Se,be]}],fill:[{fill:["none",...ne()]}],"stroke-w":[{stroke:[Ue,xo,Ba,c0]}],stroke:[{stroke:["none",...ne()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","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","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","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-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","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-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","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"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","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-pbs","scroll-pbe","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"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},wk=ZE(bk);function ve(...t){return wk(xw(t))}const ht=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("rounded-xl border bg-card text-card-foreground shadow",t),...e}));ht.displayName="Card";const zt=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("flex flex-col space-y-1.5 p-6",t),...e}));zt.displayName="CardHeader";const Lt=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("font-semibold leading-none tracking-tight",t),...e}));Lt.displayName="CardTitle";const wn=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("text-sm text-muted-foreground",t),...e}));wn.displayName="CardDescription";const xt=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("p-6 pt-0",t),...e}));xt.displayName="CardContent";const Tu=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("flex items-center p-6 pt-0",t),...e}));Tu.displayName="CardFooter";function ou({className:t}){return o.jsx("img",{src:"/folio-logo.svg",alt:"Folio Logo",className:ve("w-full h-full object-contain",t)})}const Dw=(...t)=>t.filter((e,s,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===s).join(" ").trim();const Sk=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const jk=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,s,i)=>i?i.toUpperCase():s.toLowerCase());const h0=t=>{const e=jk(t);return e.charAt(0).toUpperCase()+e.slice(1)};var _k={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Nk=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Tk=v.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:s=2,absoluteStrokeWidth:i,className:l="",children:u,iconNode:d,...h},m)=>v.createElement("svg",{ref:m,..._k,width:e,height:e,stroke:t,strokeWidth:i?Number(s)*24/Number(e):s,className:Dw("lucide",l),...!u&&!Nk(h)&&{"aria-hidden":"true"},...h},[...d.map(([p,y])=>v.createElement(p,y)),...Array.isArray(u)?u:[u]]));const me=(t,e)=>{const s=v.forwardRef(({className:i,...l},u)=>v.createElement(Tk,{ref:u,iconNode:e,className:Dw(`lucide-${Sk(h0(t))}`,`lucide-${t}`,i),...l}));return s.displayName=h0(t),s};const Ek=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],dr=me("activity",Ek);const kk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ck=me("arrow-right",kk);const Ak=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Rk=me("book-open",Ak);const Ok=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Zf=me("bot",Ok);const Mk=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],Pw=me("brain",Mk);const Dk=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],Pk=me("building-2",Dk);const zk=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],zw=me("calendar",zk);const Lk=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],Uk=me("camera",Lk);const Bk=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],as=me("check",Bk);const Vk=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Bo=me("chevron-down",Vk);const Ik=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Jo=me("chevron-left",Ik);const $k=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],hr=me("chevron-right",$k);const qk=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],lu=me("chevron-up",qk);const Hk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Sn=me("circle-alert",Hk);const Gk=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Fk=me("circle-check-big",Gk);const Kk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],os=me("circle-check",Kk);const Yk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],Lw=me("circle-x",Yk);const Xk=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Qo=me("clock",Xk);const Wk=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],f0=me("cloud",Wk);const Jk=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Qk=me("copy",Jk);const Zk=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],Bm=me("cpu",Zk);const eC=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Eu=me("database",eC);const tC=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Uw=me("external-link",tC);const nC=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],sC=me("eye-off",nC);const aC=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],iC=me("eye",aC);const rC=[["path",{d:"M4 12V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2",key:"jrl274"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 16h2v6",key:"1bxocy"}],["path",{d:"M10 22h4",key:"ceow96"}],["rect",{x:"2",y:"16",width:"4",height:"6",rx:"2",key:"r45zd0"}]],oC=me("file-digit",rC);const lC=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Vm=me("file-text",lC);const cC=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Bw=me("funnel",cC);const uC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],dC=me("globe",uC);const hC=[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]],fC=me("hard-drive",hC);const mC=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],pC=me("history",mC);const gC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Im=me("info",gC);const yC=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],Zo=me("key",yC);const vC=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],xC=me("layers",vC);const bC=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],m0=me("layout-dashboard",bC);const wC=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=me("loader-circle",wC);const SC=[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]],Vw=me("log-in",SC);const jC=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],Iw=me("log-out",jC);const _C=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],Vo=me("mail",_C);const NC=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],cu=me("message-square",NC);const TC=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],$w=me("minimize-2",TC);const EC=[["path",{d:"M5 12h14",key:"1ays0h"}]],em=me("minus",EC);const kC=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],CC=me("moon",kC);const AC=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],RC=me("package",AC);const OC=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],qw=me("play",OC);const MC=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ja=me("plus",MC);const DC=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],PC=me("refresh-ccw",DC);const zC=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],ma=me("refresh-cw",zC);const LC=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],UC=me("rocket",LC);const BC=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],VC=me("save",BC);const IC=[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]],Hw=me("scroll-text",IC);const $C=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],qC=me("search",$C);const HC=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],GC=me("send",HC);const FC=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],KC=me("server",FC);const YC=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],$m=me("settings-2",YC);const XC=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],WC=me("settings",XC);const JC=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],p0=me("share-2",JC);const QC=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],uu=me("shield-alert",QC);const ZC=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],ya=me("shield-check",ZC);const eA=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Cs=me("sparkles",eA);const tA=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],nA=me("sun",tA);const sA=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],du=me("tag",sA);const aA=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Io=me("terminal",aA);const iA=[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]],rA=me("test-tube",iA);const oA=[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],lA=me("toggle-left",oA);const cA=[["circle",{cx:"15",cy:"12",r:"3",key:"1afu0r"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],uA=me("toggle-right",cA);const dA=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],el=me("trash-2",dA);const hA=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Gw=me("triangle-alert",hA);const fA=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],tm=me("upload",fA);const mA=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],pA=me("user-plus",mA);const gA=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],ku=me("user",gA);const yA=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],nm=me("volume-2",yA);const vA=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],Fw=me("volume-x",vA);const xA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],zn=me("x",xA);const bA=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],hu=me("zap",bA),Cu="folio_supabase_config";function g0(t){if(!t||typeof t!="object")return!1;const e=t;return typeof e.url=="string"&&typeof e.anonKey=="string"&&e.url.startsWith("http")&&e.anonKey.length>20&&!e.url.includes("placeholder.supabase.co")}function $o(){try{const e=localStorage.getItem(Cu);if(e){const s=JSON.parse(e);if(g0(s))return s}}catch{}const t={url:void 0,anonKey:void 0};return g0(t)?t:null}function hf(t){localStorage.setItem(Cu,JSON.stringify(t))}function wA(){localStorage.removeItem(Cu)}async function SA(t,e){if(!t.startsWith("http://")&&!t.startsWith("https://"))return{valid:!1,error:"Invalid URL format"};const s=e.startsWith("eyJ"),i=e.startsWith("sb_publishable_");if(!s&&!i)return{valid:!1,error:"Invalid anon key format"};if(i)return{valid:!0};const l=new AbortController,u=setTimeout(()=>l.abort("Validation timeout"),12e3);try{const d=await fetch(`${t}/rest/v1/`,{method:"GET",headers:{apikey:e,Authorization:`Bearer ${e}`},signal:l.signal});return d.ok?(clearTimeout(u),{valid:!0}):(clearTimeout(u),{valid:!1,error:`Connection failed (${d.status})`})}catch(d){return clearTimeout(u),d instanceof DOMException&&d.name==="AbortError"?{valid:!1,error:"Connection validation timed out (12s). Check project URL/key and network."}:{valid:!1,error:d instanceof Error?d.message:"Connection failed"}}}function jA(){return localStorage.getItem(Cu)?"ui":"none"}let Dc=null;function un(){const t=$o();return t?(Dc||(Dc=zm(t.url,t.anonKey,{auth:{autoRefreshToken:!0,persistSession:!0}})),Dc):(Dc=null,null)}function ff(){const t=$o(),e=t?`${t.url}/functions/v1`:"",s=t?.anonKey??"",u=window.location.port==="5173"?void 0||"http://localhost:3006":window.location.origin;return{edgeFunctionsUrl:e,expressApiUrl:u,anonKey:s}}class _A{edgeFunctionsUrl;expressApiUrl;anonKey;constructor(){const e=ff();this.edgeFunctionsUrl=e.edgeFunctionsUrl,this.expressApiUrl=e.expressApiUrl,this.anonKey=e.anonKey}async request(e,s,i={}){const{auth:l=!1,token:u,...d}=i,h={"Content-Type":"application/json",...d.headers||{}};l&&u&&(h.Authorization=`Bearer ${u}`);try{const m=await fetch(`${e}${s}`,{...d,headers:h}),p=await m.json().catch(()=>({}));return m.ok?{data:p}:{error:{code:p?.error?.code||"API_ERROR",message:p?.error?.message||p?.error||`Request failed (${m.status})`}}}catch(m){return{error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}edgeRequest(e,s={}){const i={...s.headers||{},apikey:this.anonKey};return this.request(this.edgeFunctionsUrl,e,{...s,headers:i})}expressRequest(e,s={}){const i=ff(),l={...s.headers||{},"X-Supabase-Url":i.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":i.anonKey};return this.request(this.expressApiUrl,e,{...s,headers:l})}get(e,s={}){return this.expressRequest(e,{method:"GET",...s,auth:!0})}post(e,s,i={}){return this.expressRequest(e,{method:"POST",body:s?JSON.stringify(s):void 0,...i,auth:!0})}getChatSessions(e){return this.expressRequest("/api/chat/sessions",{method:"GET",auth:!!e,token:e})}getDashboardStats(e){return this.expressRequest("/api/stats",{method:"GET",auth:!!e,token:e})}createChatSession(e){return this.expressRequest("/api/chat/sessions",{method:"POST",auth:!!e,token:e})}getChatMessages(e,s){return this.expressRequest(`/api/chat/sessions/${e}/messages`,{method:"GET",auth:!!s,token:s})}sendChatMessage(e,s){return this.expressRequest("/api/chat/message",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}getHealth(){return this.expressRequest("/api/health",{method:"GET"})}testSupabase(e,s){return this.expressRequest("/api/setup/test-supabase",{method:"POST",body:JSON.stringify({url:e,anonKey:s})})}dispatchProcessingJob(e,s){return this.expressRequest("/api/processing/dispatch",{method:"POST",auth:!!s,token:s,body:JSON.stringify({source_type:"manual",payload:e})})}getSettings(e){return this.expressRequest("/api/settings",{method:"GET",auth:!!e,token:e})}updateSettings(e,s){return this.expressRequest("/api/settings",{method:"PATCH",auth:!!s,token:s,body:JSON.stringify(e)})}getAccounts(e){return this.expressRequest("/api/accounts",{method:"GET",auth:!!e,token:e})}disconnectAccount(e,s){return this.expressRequest("/api/accounts/disconnect",{method:"POST",auth:!!s,token:s,body:JSON.stringify({accountId:e})})}getRules(e){return this.expressRequest("/api/rules",{method:"GET",auth:!!e,token:e})}createRule(e,s){return this.expressRequest("/api/rules",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}updateRule(e,s,i){return this.expressRequest(`/api/rules/${e}`,{method:"PATCH",auth:!!i,token:i,body:JSON.stringify(s)})}deleteRule(e,s){return this.expressRequest(`/api/rules/${e}`,{method:"DELETE",auth:!!s,token:s})}toggleRule(e,s){return this.expressRequest(`/api/rules/${e}/toggle`,{method:"POST",auth:!!s,token:s})}getStats(e){return this.expressRequest("/api/stats",{method:"GET",auth:!!e,token:e})}getProfile(e){return this.edgeRequest("/api-v1-profile",{method:"GET",auth:!!e,token:e})}updateProfile(e,s){return this.edgeRequest("/api-v1-profile",{method:"PATCH",auth:!!s,token:s,body:JSON.stringify(e)})}getChatProviders(e){return this.expressRequest("/api/sdk/providers/chat",{method:"GET",auth:!!e,token:e})}getEmbedProviders(e){return this.expressRequest("/api/sdk/providers/embed",{method:"GET",auth:!!e,token:e})}testLlm(e,s){return this.expressRequest("/api/sdk/test-llm",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}getGmailAuthUrl(e,s,i){return this.expressRequest("/api/accounts/gmail/auth-url",{method:"POST",auth:!!i,token:i,body:JSON.stringify({clientId:e,clientSecret:s})})}connectGmail(e,s,i,l){return this.expressRequest("/api/accounts/gmail/connect",{method:"POST",auth:!!l,token:l,body:JSON.stringify({authCode:e,clientId:s,clientSecret:i})})}getGoogleDriveAuthUrl(e,s){return this.expressRequest("/api/accounts/google-drive/auth-url",{method:"POST",auth:!!s,token:s,body:JSON.stringify({clientId:e})})}connectGoogleDrive(e,s,i,l){return this.expressRequest("/api/accounts/google-drive/connect",{method:"POST",auth:!!l,token:l,body:JSON.stringify({authCode:e,clientId:s,clientSecret:i})})}startMicrosoftDeviceFlow(e,s,i){return this.expressRequest("/api/accounts/microsoft/device-flow",{method:"POST",auth:!!i,token:i,body:JSON.stringify({clientId:e,tenantId:s})})}pollMicrosoftDeviceCode(e,s,i,l){return this.expressRequest("/api/accounts/microsoft/poll",{method:"POST",auth:!!l,token:l,body:JSON.stringify({deviceCode:e,clientId:s,tenantId:i})})}connectImap(e,s){return this.expressRequest("/api/accounts/imap/connect",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}setup(e){return this.edgeRequest("/setup",{method:"POST",body:JSON.stringify(e)})}getPolicies(e){return this.expressRequest("/api/policies",{auth:!!e,token:e})}savePolicy(e,s){return this.expressRequest("/api/policies",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}deletePolicy(e,s){return this.expressRequest(`/api/policies/${e}`,{method:"DELETE",auth:!!s,token:s})}patchPolicy(e,s,i){return this.expressRequest(`/api/policies/${e}`,{method:"PATCH",auth:!!i,token:i,body:JSON.stringify(s)})}reloadPolicies(e){return this.expressRequest("/api/policies/reload",{method:"POST",auth:!!e,token:e})}synthesizePolicy(e,s){return this.expressRequest("/api/policies/synthesize",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}getSDKChatProviders(){return this.expressRequest("/api/sdk/providers/chat")}getIngestions(e={},s){const i=new URLSearchParams;e.page&&i.set("page",String(e.page)),e.pageSize&&i.set("pageSize",String(e.pageSize)),e.q&&i.set("q",e.q);const l=i.toString()?`?${i}`:"";return this.expressRequest(`/api/ingestions${l}`,{auth:!!s,token:s})}uploadDocument(e,s){const i=new FormData;i.append("file",e);const l=ff(),u={"X-Supabase-Url":l.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":l.anonKey};return s&&(u.Authorization=`Bearer ${s}`),fetch(`${l.expressApiUrl}/api/ingestions/upload`,{method:"POST",headers:u,body:i}).then(d=>d.json())}rerunIngestion(e,s){return this.expressRequest(`/api/ingestions/${e}/rerun`,{method:"POST",auth:!!s,token:s})}matchIngestionToPolicy(e,s,i){const l=s.learn!==!1,u=s.rerun!==!1;return this.expressRequest(`/api/ingestions/${e}/match`,{method:"POST",auth:!!i,token:i,body:JSON.stringify({policy_id:s.policyId,learn:l,rerun:u,allow_side_effects:s.allowSideEffects===!0})})}suggestPolicyRefinement(e,s,i){return this.expressRequest(`/api/ingestions/${e}/refine-policy`,{method:"POST",auth:!!i,token:i,body:JSON.stringify({policy_id:s.policyId,provider:s.provider,model:s.model})})}deleteIngestion(e,s){return this.expressRequest(`/api/ingestions/${e}`,{method:"DELETE",auth:!!s,token:s})}updateIngestionTags(e,s,i){return this.expressRequest(`/api/ingestions/${e}/tags`,{method:"PATCH",auth:!!i,token:i,body:JSON.stringify({tags:s})})}summarizeIngestion(e,s){return this.expressRequest(`/api/ingestions/${e}/summarize`,{method:"POST",auth:!!s,token:s})}getBaselineConfig(e){return this.expressRequest("/api/baseline-config",{auth:!!e,token:e})}getBaselineConfigHistory(e){return this.expressRequest("/api/baseline-config/history",{auth:!!e,token:e})}saveBaselineConfig(e,s){return this.expressRequest("/api/baseline-config",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}activateBaselineConfig(e,s){return this.expressRequest(`/api/baseline-config/${e}/activate`,{method:"POST",auth:!!s,token:s})}suggestBaselineConfig(e,s){return this.expressRequest("/api/baseline-config/suggest",{method:"POST",auth:!!s,token:s,body:JSON.stringify(e)})}}const Ee=new _A;let ns=[],sm=new Set;function am(){sm.forEach(t=>t())}const ue={success:(t,e)=>Pc("success",t,e),error:(t,e)=>Pc("error",t,e),info:(t,e)=>Pc("info",t,e),warning:(t,e)=>Pc("warning",t,e)};function Pc(t,e,s=5e3){const i=ns.findIndex(u=>u.message===e&&u.type===t);if(i!==-1){const u=ns[i];ns=[...ns],ns[i]={...u,count:(u.count||1)+1,lastUpdated:Date.now()},am();return}const l=Math.random().toString(36).substr(2,9);ns=[...ns,{id:l,type:t,message:e,duration:s,count:1,lastUpdated:Date.now()}],am(),s>0&&setTimeout(()=>Kw(l),s)}function Kw(t){ns=ns.filter(e=>e.id!==t),am()}function NA(){const[,t]=v.useState(0);return v.useEffect(()=>{const e=()=>t(s=>s+1);return sm.add(e),()=>{sm.delete(e)}},[]),ns}const TA={success:Fk,error:Sn,info:Im,warning:Gw},EA={success:"bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400",error:"bg-destructive/10 border-destructive/20 text-destructive",info:"bg-blue-500/10 border-blue-500/20 text-blue-600 dark:text-blue-400",warning:"bg-yellow-500/10 border-yellow-500/20 text-yellow-600 dark:text-yellow-400"};function kA({toast:t}){const e=TA[t.type];return o.jsxs("div",{className:ve("flex items-start gap-3 p-4 rounded-lg border shadow-lg backdrop-blur-sm","animate-in slide-in-from-left-full duration-300",EA[t.type]),children:[o.jsxs("div",{className:"relative",children:[o.jsx(e,{className:"w-5 h-5 flex-shrink-0 mt-0.5"}),t.count&&t.count>1&&o.jsx("span",{className:"absolute -top-2 -right-2 bg-primary text-primary-foreground text-[10px] font-bold px-1.5 rounded-full border border-background scale-90 animate-in zoom-in duration-200",children:t.count})]}),o.jsx("p",{className:"text-sm flex-1",children:t.message}),o.jsx("button",{onClick:()=>Kw(t.id),className:"p-1 hover:bg-black/10 rounded transition-colors",children:o.jsx(zn,{className:"w-4 h-4"})})]})}function CA(){const t=NA();return t.length===0?null:o.jsx("div",{className:"fixed bottom-4 left-4 z-[100] flex flex-col-reverse gap-2 max-w-sm w-full",children:t.map(e=>o.jsx(kA,{toast:e},e.id))})}function AA({configSnapshot:t,configSource:e,setActivePage:s}){const[i,l]=v.useState(null),[u,d]=v.useState(!0),[h,m]=v.useState(!1),[p,y]=v.useState(!1),x=v.useRef(null),w=v.useCallback(async()=>{d(!0);try{const S=un();if(!S)return;const{data:_}=await S.auth.getSession(),E=_.session?.access_token??null;if(!E)return;const C=await Ee.getDashboardStats(E);C.data?.success&&l(C.data.stats)}catch(S){console.error("Failed to fetch dashboard stats",S)}finally{d(!1)}},[]);v.useEffect(()=>{w()},[w]);const j=async S=>{const _=Array.from(S);if(_.length){s("funnel"),y(!0);try{const E=un();if(!E)return;const{data:C}=await E.auth.getSession(),A=C.session?.access_token??null;if(!A)return;for(const k of _){ue.info(`Ingesting ${k.name}…`);const M=await Ee.uploadDocument?.(k,A);if(M?.success)if(M.ingestion?.status==="duplicate"){const P=M.ingestion.extracted?.original_filename??"a previous upload";ue.warning(`${k.name} is a duplicate of "${P}" — skipped.`)}else ue.success(`${k.name} → ${M.ingestion?.status}`);else ue.error(`Failed to ingest ${k.name}`)}await w()}finally{y(!1)}}},T=S=>{S.preventDefault(),m(!1),j(S.dataTransfer.files)};return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-12 animate-in fade-in duration-700",children:[o.jsxs("div",{className:"text-center space-y-3",children:[o.jsxs("h2",{className:"text-4xl font-black tracking-tight flex items-center justify-center gap-3",children:[o.jsx(ou,{className:"w-10 h-10 animate-pulse"}),"Command Center"]}),o.jsx("p",{className:"text-muted-foreground text-lg max-w-2xl mx-auto",children:"Central intelligence hub for document ingestion, routing, and synthetic knowledge."})]}),o.jsxs("div",{className:"w-full space-y-10",children:[o.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[o.jsx(zc,{title:"Documents Ingested",value:i?.totalDocuments,icon:o.jsx(Vm,{className:"w-5 h-5 text-blue-500"}),isLoading:u,colorClass:"bg-blue-500/10"}),o.jsx(zc,{title:"Active Policies",value:i?.activePolicies,icon:o.jsx(p0,{className:"w-5 h-5 text-emerald-500"}),isLoading:u,colorClass:"bg-emerald-500/10"}),o.jsx(zc,{title:"Knowledge Chunks",value:i?.ragChunks,icon:o.jsx(Eu,{className:"w-5 h-5 text-purple-500"}),isLoading:u,colorClass:"bg-purple-500/10"}),o.jsx(zc,{title:"Automation Runs",value:i?.automationRuns,icon:o.jsx(dr,{className:"w-5 h-5 text-amber-500"}),isLoading:u,colorClass:"bg-amber-500/10"})]}),o.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[o.jsx("div",{className:"lg:col-span-2",children:o.jsxs("div",{onDragOver:S=>{S.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:T,onClick:()=>x.current?.click(),className:ve("h-full rounded-2xl border-2 border-dashed transition-all cursor-pointer flex flex-col items-center justify-center gap-4 py-16",h?"border-primary bg-primary/5 scale-[1.01]":"border-muted-foreground/20 hover:border-primary/50 hover:bg-muted/30"),children:[o.jsx("input",{ref:x,type:"file",multiple:!0,hidden:!0,onChange:S=>S.target.files&&j(S.target.files)}),p?o.jsx(rt,{className:"w-12 h-12 animate-spin text-primary"}):o.jsx(tm,{className:ve("w-12 h-12 transition-colors",h?"text-primary":"text-muted-foreground/50")}),o.jsxs("div",{className:"text-center space-y-1",children:[o.jsx("p",{className:"text-lg font-medium text-foreground",children:h?"Drop to ingest...":"Drag & drop files to ingest"}),o.jsx("p",{className:"text-sm text-muted-foreground/60",children:"Supports .pdf, .docx, .md, .txt (up to 20MB)"})]})]})}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs(ht,{className:"flex-1 cursor-pointer hover:border-primary/50 hover:bg-muted/30 transition-all flex flex-col items-center justify-center p-6 text-center shadow-sm",onClick:()=>s("chat"),children:[o.jsx("div",{className:"w-12 h-12 rounded-xl bg-indigo-500/10 flex items-center justify-center mb-4",children:o.jsx(cu,{className:"w-6 h-6 text-indigo-500"})}),o.jsx("h3",{className:"font-bold mb-1",children:"Chat with Data"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask questions against your vectorized knowledge base."})]}),o.jsxs(ht,{className:"flex-1 cursor-pointer hover:border-primary/50 hover:bg-muted/30 transition-all flex flex-col items-center justify-center p-6 text-center shadow-sm",onClick:()=>s("policies"),children:[o.jsx("div",{className:"w-12 h-12 rounded-xl bg-orange-500/10 flex items-center justify-center mb-4",children:o.jsx(p0,{className:"w-6 h-6 text-orange-500"})}),o.jsx("h3",{className:"font-bold mb-1",children:"Create Policy"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Define a new routing and automation contract."})]})]})]})]})]})}function zc({title:t,value:e,icon:s,isLoading:i,colorClass:l}){return o.jsx(ht,{className:"shadow-sm",children:o.jsxs(xt,{className:"p-6",children:[o.jsx("div",{className:"flex items-center justify-between mb-4",children:o.jsx("div",{className:ve("w-10 h-10 rounded-xl flex items-center justify-center",l),children:s})}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("p",{className:"text-sm text-muted-foreground font-medium",children:t}),i?o.jsx("div",{className:"h-8 w-16 bg-muted animate-pulse rounded-md"}):o.jsx("p",{className:"text-3xl font-black",children:e!==void 0?e.toLocaleString():"0"})]})]})})}function y0(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Au(...t){return e=>{let s=!1;const i=t.map(l=>{const u=y0(l,e);return!s&&typeof u=="function"&&(s=!0),u});if(s)return()=>{for(let l=0;l<i.length;l++){const u=i[l];typeof u=="function"?u():y0(t[l],null)}}}}function si(...t){return v.useCallback(Au(...t),t)}var RA=Symbol.for("react.lazy"),fu=Mm[" use ".trim().toString()];function OA(t){return typeof t=="object"&&t!==null&&"then"in t}function Yw(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===RA&&"_payload"in t&&OA(t._payload)}function Xw(t){const e=DA(t),s=v.forwardRef((i,l)=>{let{children:u,...d}=i;Yw(u)&&typeof fu=="function"&&(u=fu(u._payload));const h=v.Children.toArray(u),m=h.find(zA);if(m){const p=m.props.children,y=h.map(x=>x===m?v.Children.count(p)>1?v.Children.only(null):v.isValidElement(p)?p.props.children:null:x);return o.jsx(e,{...d,ref:l,children:v.isValidElement(p)?v.cloneElement(p,void 0,y):null})}return o.jsx(e,{...d,ref:l,children:u})});return s.displayName=`${t}.Slot`,s}var MA=Xw("Slot");function DA(t){const e=v.forwardRef((s,i)=>{let{children:l,...u}=s;if(Yw(l)&&typeof fu=="function"&&(l=fu(l._payload)),v.isValidElement(l)){const d=UA(l),h=LA(u,l.props);return l.type!==v.Fragment&&(h.ref=i?Au(i,d):d),v.cloneElement(l,h)}return v.Children.count(l)>1?v.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var PA=Symbol("radix.slottable");function zA(t){return v.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===PA}function LA(t,e){const s={...e};for(const i in e){const l=t[i],u=e[i];/^on[A-Z]/.test(i)?l&&u?s[i]=(...h)=>{const m=u(...h);return l(...h),m}:l&&(s[i]=l):i==="style"?s[i]={...l,...u}:i==="className"&&(s[i]=[l,u].filter(Boolean).join(" "))}return{...t,...s}}function UA(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning;return s?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning,s?t.props.ref:t.props.ref||t.ref)}const v0=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,x0=xw,qm=(t,e)=>s=>{var i;if(e?.variants==null)return x0(t,s?.class,s?.className);const{variants:l,defaultVariants:u}=e,d=Object.keys(l).map(p=>{const y=s?.[p],x=u?.[p];if(y===null)return null;const w=v0(y)||v0(x);return l[p][w]}),h=s&&Object.entries(s).reduce((p,y)=>{let[x,w]=y;return w===void 0||(p[x]=w),p},{}),m=e==null||(i=e.compoundVariants)===null||i===void 0?void 0:i.reduce((p,y)=>{let{class:x,className:w,...j}=y;return Object.entries(j).every(T=>{let[S,_]=T;return Array.isArray(_)?_.includes({...u,...h}[S]):{...u,...h}[S]===_})?[...p,x,w]:p},[]);return x0(t,d,m,s?.class,s?.className)},BA=qm("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[color,box-shadow] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 focus-visible:ring-4 focus-visible:outline-1 aria-invalid:focus-visible:ring-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-sm hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90",outline:"border border-input bg-background shadow-xs hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),ae=v.forwardRef(({className:t,variant:e,size:s,asChild:i=!1,...l},u)=>{const d=i?MA:"button";return o.jsx(d,{className:ve(BA({variant:e,size:s,className:t})),ref:u,...l})});ae.displayName="Button";const _e=v.forwardRef(({className:t,type:e,...s},i)=>o.jsx("input",{type:e,className:ve("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:i,...s}));_e.displayName="Input";var Ww=tw();const VA=Zb(Ww);var IA=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],$A=IA.reduce((t,e)=>{const s=Xw(`Primitive.${e}`),i=v.forwardRef((l,u)=>{const{asChild:d,...h}=l,m=d?s:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(m,{...h,ref:u})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{}),qA="Label",Jw=v.forwardRef((t,e)=>o.jsx($A.label,{...t,ref:e,onMouseDown:s=>{s.target.closest("button, input, select, textarea")||(t.onMouseDown?.(s),!s.defaultPrevented&&s.detail>1&&s.preventDefault())}}));Jw.displayName=qA;var HA=Jw;function Je({className:t,...e}){return o.jsx(HA,{"data-slot":"label",className:ve("flex items-center gap-2 text-sm leading-none font-medium select-none text-muted-foreground group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...e})}const GA=qm("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Mt({className:t,variant:e,...s}){return o.jsx("div",{className:ve(GA({variant:e}),t),...s})}const FA=qm("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),jn=v.forwardRef(({className:t,variant:e,...s},i)=>o.jsx("div",{ref:i,role:"alert",className:ve(FA({variant:e}),t),...s}));jn.displayName="Alert";const Hm=v.forwardRef(({className:t,...e},s)=>o.jsx("h5",{ref:s,className:ve("mb-1 font-medium leading-none tracking-tight",t),...e}));Hm.displayName="AlertTitle";const _n=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("text-sm [&_p]:leading-relaxed",t),...e}));_n.displayName="AlertDescription";function KA({supabase:t,initStatus:e,sessionStatus:s,sessionEmail:i,onRefresh:l}){const[u,d]=v.useState(""),[h,m]=v.useState(""),[p,y]=v.useState(""),[x,w]=v.useState(""),[j,T]=v.useState(!1),[S,_]=v.useState(null),E=e==="empty";async function C(){T(!0),_(null);const{error:P}=await t.auth.signInWithPassword({email:u,password:h});P?_(P.message):l(),T(!1)}async function A(){T(!0),_(null);try{const P=await Ee.setup({email:u,password:h,first_name:p,last_name:x});if(P.error)throw new Error(typeof P.error=="string"?P.error:P.error.message);const{error:B}=await t.auth.signInWithPassword({email:u,password:h});if(B)throw B;l()}catch(P){_(P.message||"Failed to initialize foundation.")}finally{T(!1)}}async function k(){T(!0),_(null);const{error:P}=await t.auth.signUp({email:u,password:h,options:{data:{first_name:p,last_name:x}}});P?_(P.message):l(),T(!1)}async function M(){T(!0),await t.auth.signOut(),l(),T(!1)}return s==="authenticated"?o.jsxs("div",{className:"space-y-4 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex items-center gap-4 p-4 rounded-xl bg-primary/5 border border-primary/10",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-primary flex items-center justify-center text-primary-foreground",children:o.jsx(ku,{className:"w-5 h-5"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-xs font-bold uppercase tracking-widest text-muted-foreground leading-none mb-1",children:"Authenticated as"}),o.jsx("p",{className:"text-sm font-medium truncate",children:i})]})]}),e==="missing_view"&&o.jsxs(jn,{variant:"destructive",className:"bg-destructive/5 text-destructive border-destructive/20",children:[o.jsx(uu,{className:"w-4 h-4"}),o.jsx(_n,{className:"text-xs",children:"Database views missing. Foundation may be corrupted."})]}),o.jsxs(ae,{variant:"outline",className:"w-full h-11 hover:bg-destructive hover:text-destructive-reveal group transition-all duration-300",onClick:M,disabled:j,children:[j?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(Iw,{className:"w-4 h-4 mr-2 group-hover:rotate-180 transition-transform duration-500"}),"Logout Protocol"]})]}):o.jsxs("div",{className:"space-y-4 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"grid gap-4",children:[E&&o.jsxs("div",{className:"grid grid-cols-2 gap-4 animate-in slide-in-from-top-2 duration-300",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-firstname",children:"First Name"}),o.jsx(_e,{id:"auth-firstname",placeholder:"Agent",value:p,onChange:P=>y(P.target.value),className:"h-10"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-lastname",children:"Last Name"}),o.jsx(_e,{id:"auth-lastname",placeholder:"Zero",value:x,onChange:P=>w(P.target.value),className:"h-10"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-email",children:"Email Address"}),o.jsxs("div",{className:"relative",children:[o.jsx(Vo,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(_e,{id:"auth-email",type:"email",placeholder:"admin@example.com",value:u,onChange:P=>d(P.target.value),className:"pl-9 h-10"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"auth-password",children:"Security Key"}),o.jsxs("div",{className:"relative",children:[o.jsx(Zo,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(_e,{id:"auth-password",type:"password",placeholder:"••••••••",value:h,onChange:P=>m(P.target.value),className:"pl-9 h-10",autoComplete:E?"new-password":"current-password"})]})]})]}),S&&o.jsx(jn,{variant:"destructive",className:"py-2 px-3",children:o.jsx(_n,{className:"text-[11px] leading-relaxed italic",children:S})}),o.jsx("div",{className:"pt-2",children:E?o.jsxs(ae,{className:"w-full h-11 shadow-lg shadow-primary/20",onClick:A,disabled:j||!u||!h||!p,children:[j?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(ya,{className:"w-4 h-4 mr-2"}),"Initialize Primary Admin"]}):o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs(ae,{className:"h-10",onClick:C,disabled:j||!u||!h,children:[j?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(Vw,{className:"w-4 h-4 mr-2"}),"Login"]}),o.jsxs(ae,{variant:"secondary",className:"h-10",onClick:k,disabled:j||!u||!h,children:[o.jsx(pA,{className:"w-4 h-4 mr-2"}),"Enroll"]})]})}),o.jsx("p",{className:"text-[10px] text-center text-muted-foreground uppercase tracking-widest font-bold opacity-50 pt-2",children:E?"Foundation Assembly Phase":"Foundation Access Required"})]})}const ha="0.1.16",YA="20260302000000";async function XA(t,e){const s=Promise.resolve(t);let i=null;const l=new Promise((u,d)=>{i=setTimeout(()=>{d(new Error(`Operation timed out after ${e}ms`))},e)});try{return await Promise.race([s,l])}finally{i&&clearTimeout(i)}}async function WA(t){try{const{data:e,error:s}=await XA(t.rpc("get_latest_migration_timestamp"),12e3);if(s)return s.code==="42883"?{latestMigrationTimestamp:"0"}:{latestMigrationTimestamp:null};const i=e??null;return i&&i>="29990000000000"?{latestMigrationTimestamp:null}:{latestMigrationTimestamp:i}}catch{return{latestMigrationTimestamp:null}}}async function Qw(t){const e=await WA(t);return!e.latestMigrationTimestamp||e.latestMigrationTimestamp.trim()===""?{needsMigration:!0,appVersion:ha,latestMigrationTimestamp:e.latestMigrationTimestamp,message:"Database migration state unknown."}:YA>e.latestMigrationTimestamp?{needsMigration:!0,appVersion:ha,latestMigrationTimestamp:e.latestMigrationTimestamp,message:`Database is behind (${e.latestMigrationTimestamp}).`}:{needsMigration:!1,appVersion:ha,latestMigrationTimestamp:e.latestMigrationTimestamp,message:"Database schema is up-to-date."}}function JA({supabase:t,sessionEmail:e,sessionStatus:s,initStatus:i,configSnapshot:l,configSource:u,onRefresh:d,onLaunchSetup:h,onResetSetup:m}){const[p,y]=v.useState("profile"),[x,w]=v.useState(null),[j,T]=v.useState(!1);async function S(){if(!t)return;T(!0);const{data:{user:C}}=await t.auth.getUser();if(C){const{data:A}=await t.from("profiles").select("*").eq("id",C.id).single();A&&w(A)}T(!1)}v.useEffect(()=>{s==="authenticated"&&t&&S()},[s,t]);const _=[{id:"profile",label:"Profile",icon:ku},{id:"security",label:"Security",icon:ya},{id:"supabase",label:"Supabase",icon:Eu}];async function E(){t&&(await t.auth.signOut(),d())}return o.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-in fade-in duration-700",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h1",{className:"text-4xl font-black tracking-tight",children:"Account Settings"}),o.jsx("p",{className:"text-muted-foreground text-lg",children:"Manage your profile and foundational preferences."})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-12 items-start",children:[o.jsxs("aside",{className:"w-full md:w-72 flex flex-col gap-8 shrink-0",children:[o.jsx("nav",{className:"space-y-1",children:_.map(C=>{const A=C.icon,k=p===C.id;return o.jsxs("button",{onClick:()=>y(C.id),className:ve("w-full flex items-center gap-3 px-4 py-3 text-sm font-bold rounded-xl transition-all duration-300",k?"bg-foreground text-background shadow-lg shadow-foreground/10":"text-muted-foreground hover:bg-muted/60 hover:text-foreground"),children:[o.jsx(A,{className:ve("w-5 h-5",k?"text-background":"text-muted-foreground/60")}),C.label]},C.id)})}),o.jsxs("div",{className:"pt-8 border-t space-y-6",children:[o.jsxs("button",{onClick:E,className:"group w-full flex items-center gap-3 px-4 py-2 text-sm font-bold rounded-xl transition-all duration-300 text-destructive hover:bg-destructive/10",children:[o.jsx(Iw,{className:"w-5 h-5 transition-transform group-hover:translate-x-1"}),"Logout"]}),o.jsxs("div",{className:"px-4",children:[o.jsx("p",{className:"text-[10px] font-black text-muted-foreground/40 uppercase tracking-widest mb-1",children:"Version"}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/60",children:["v",ha]})]})]})]}),o.jsxs("div",{className:"flex-1 w-full animate-in slide-in-from-right-4 duration-500",children:[p==="profile"&&o.jsx(QA,{sessionEmail:e,sessionStatus:s,supabase:t,initStatus:i,profile:x,onProfileUpdate:S,onRefresh:d,isLoading:j}),p==="security"&&o.jsx(ZA,{supabase:t}),p==="supabase"&&o.jsx(eR,{configSnapshot:l,configSource:u,onLaunchSetup:h,onResetSetup:m})]})]})]})}function QA({sessionEmail:t,sessionStatus:e,supabase:s,initStatus:i,profile:l,onProfileUpdate:u,onRefresh:d,isLoading:h}){const[m,p]=v.useState(""),[y,x]=v.useState(""),[w,j]=v.useState(!0),[T,S]=v.useState(!1),[_,E]=v.useState(!1);v.useEffect(()=>{l&&(p(l.first_name||""),x(l.last_name||""))},[l]);const C=async()=>{if(!s||!l)return;S(!0);const{error:k}=await s.from("profiles").update({first_name:m,last_name:y}).eq("id",l.id);k||u(),S(!1)},A=async k=>{const M=k.target.files?.[0];if(!(!M||!s||!l)){E(!0);try{const P=M.name.split(".").pop(),B=`${l.id}/${Math.random()}.${P}`,{error:R}=await s.storage.from("avatars").upload(B,M);if(R)throw R;const{data:{publicUrl:I}}=s.storage.from("avatars").getPublicUrl(B);await s.from("profiles").update({avatar_url:I}).eq("id",l.id),u()}catch(P){console.error("Upload error:",P)}finally{E(!1)}}};return o.jsxs(ht,{className:"border-border/40 shadow-xl shadow-black/5 bg-card/50 backdrop-blur-sm overflow-hidden",children:[o.jsxs(zt,{className:"p-8 border-b bg-muted/20",children:[o.jsx(Lt,{className:"text-2xl font-black",children:"Profile Information"}),o.jsx(wn,{className:"text-base",children:"Update your personal foundation details."})]}),o.jsx(xt,{className:"p-8 space-y-10",children:h?o.jsx("div",{className:"flex items-center justify-center py-12",children:o.jsx(rt,{className:"w-8 h-8 animate-spin text-primary"})}):e==="authenticated"?o.jsxs("div",{className:"space-y-10",children:[o.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-8",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("div",{className:"w-32 h-32 rounded-full bg-primary/10 border-4 border-background shadow-2xl overflow-hidden flex items-center justify-center",children:l?.avatar_url?o.jsx("img",{src:l.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):t?o.jsx("span",{className:"text-4xl font-black text-primary",children:t.charAt(0).toUpperCase()}):o.jsx(ku,{className:"w-12 h-12 text-primary/40"})}),o.jsxs("label",{className:"absolute bottom-1 right-1 h-10 w-10 rounded-full bg-background border shadow-lg flex items-center justify-center hover:scale-110 transition-transform cursor-pointer",children:[_?o.jsx(rt,{className:"w-4 h-4 animate-spin text-muted-foreground"}):o.jsx(Uk,{className:"w-5 h-5 text-muted-foreground"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:A,disabled:_})]})]}),o.jsxs("div",{className:"flex-1 w-full grid grid-cols-1 sm:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"firstName",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"First Name"}),o.jsx(_e,{id:"firstName",placeholder:"Trung",value:m,onChange:k=>p(k.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"lastName",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"Last Name"}),o.jsx(_e,{id:"lastName",placeholder:"Le",value:y,onChange:k=>x(k.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]}),o.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[o.jsx(Je,{htmlFor:"email",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"Email Address"}),o.jsx(_e,{id:"email",value:t||"",disabled:!0,className:"h-12 rounded-xl bg-muted/40 border-border/40 opacity-70 cursor-not-allowed"}),o.jsx("p",{className:"text-[10px] text-muted-foreground/60 font-bold ml-1",children:"This is your login email and cannot be changed."})]})]})]}),o.jsxs("div",{className:"pt-8 border-t flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h4",{className:"text-base font-bold",children:"Sound & Haptic Feedback"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Play chimes and haptic pulses for system events."})]}),o.jsxs(ae,{variant:w?"default":"outline",className:ve("h-11 px-6 rounded-xl font-bold transition-all",w?"shadow-lg shadow-primary/20":""),onClick:()=>j(!w),children:[w?o.jsx(nm,{className:"w-4 h-4 mr-2"}):o.jsx(Fw,{className:"w-4 h-4 mr-2"}),w?"Enabled":"Disabled"]})]})]}):o.jsxs("div",{className:"py-8",children:[o.jsxs("div",{className:"flex items-center gap-3 border-b pb-4 mb-6",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary",children:o.jsx(ya,{className:"w-6 h-6"})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-bold",children:"Authentication Gateway"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Access your foundational profile."})]})]}),s&&o.jsx(KA,{supabase:s,initStatus:i,sessionStatus:e,sessionEmail:t,onRefresh:d})]})}),e==="authenticated"&&!h&&o.jsx(Tu,{className:"bg-muted/20 p-8 flex justify-end",children:o.jsxs(ae,{className:"h-12 px-8 rounded-xl font-bold shadow-xl shadow-primary/20",onClick:C,disabled:T,children:[T?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(VC,{className:"w-4 h-4 mr-2"}),"Save Changes"]})})]})}function ZA({supabase:t}){const[e,s]=v.useState(""),[i,l]=v.useState(""),[u,d]=v.useState(!1),[h,m]=v.useState(null),p=async()=>{if(!t)return;if(e!==i){m({type:"error",msg:"Passwords do not match."});return}if(e.length<8){m({type:"error",msg:"Password must be at least 8 characters."});return}d(!0),m(null);const{error:y}=await t.auth.updateUser({password:e});y?m({type:"error",msg:y.message}):(m({type:"success",msg:"Password updated successfully."}),s(""),l("")),d(!1)};return o.jsxs(ht,{className:"border-border/40 shadow-xl shadow-black/5 bg-card/50 backdrop-blur-sm overflow-hidden",children:[o.jsxs(zt,{className:"p-8 border-b bg-muted/20",children:[o.jsx(Lt,{className:"text-2xl font-black",children:"Security Protocol"}),o.jsx(wn,{className:"text-base",children:"Manage your foundation credentials and access keys."})]}),o.jsxs(xt,{className:"p-8 space-y-8",children:[h&&o.jsxs(jn,{variant:h.type==="error"?"destructive":"default",className:ve("animate-in fade-in slide-in-from-top-2 duration-300",h.type==="success"?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20":""),children:[h.type==="success"?o.jsx(os,{className:"h-4 w-4"}):o.jsx(uu,{className:"h-4 w-4"}),o.jsx(_n,{className:"text-sm font-bold",children:h.msg})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-8",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"newPass",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"New Password"}),o.jsx(_e,{id:"newPass",type:"password",placeholder:"••••••••",value:e,onChange:y=>s(y.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"confirmPass",className:"text-xs font-black uppercase tracking-widest text-muted-foreground ml-1",children:"Confirm Password"}),o.jsx(_e,{id:"confirmPass",type:"password",placeholder:"••••••••",value:i,onChange:y=>l(y.target.value),className:"h-12 rounded-xl bg-background/50 border-border/40"})]})]}),o.jsxs("div",{className:"bg-muted/30 p-6 rounded-2xl border border-border/40 space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary",children:o.jsx(uu,{className:"w-5 h-5"})}),o.jsx("h5",{className:"font-bold",children:"Security Tip"})]}),o.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Use a password at least 12 characters long with a mix of letters, numbers, and symbols to ensure your foundational data remains secure."})]})]})]}),o.jsx(Tu,{className:"bg-muted/20 p-8 flex justify-end",children:o.jsxs(ae,{className:"h-12 px-8 rounded-xl font-bold shadow-xl shadow-primary/20",onClick:p,disabled:u||!e||!i,children:[u?o.jsx(rt,{className:"w-4 h-4 animate-spin mr-2"}):o.jsx(Zo,{className:"w-4 h-4 mr-2"}),"Update Password"]})})]})}function eR({configSnapshot:t,configSource:e,onLaunchSetup:s,onResetSetup:i}){return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-700",children:[o.jsxs("div",{className:"flex items-center gap-3 border-b pb-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary",children:o.jsx(Eu,{className:"w-6 h-6"})}),o.jsxs("div",{className:"flex-1",children:[o.jsx("h3",{className:"text-lg font-bold",children:"Supabase Configuration"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Primary storage and identity gateway."})]}),o.jsxs(Mt,{variant:"secondary",className:"text-[10px] font-black uppercase tracking-widest px-3 py-1",children:["Source: ",e]})]}),o.jsxs(ht,{className:"border-border/40 shadow-sm bg-card/50 backdrop-blur-sm",children:[o.jsx(xt,{className:"p-8 space-y-8",children:t?o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("span",{className:"text-[10px] font-black uppercase text-muted-foreground tracking-widest pl-1",children:"API Endpoint"}),o.jsx("div",{className:"bg-muted/30 p-4 rounded-2xl border border-border/40 backdrop-blur-sm shadow-inner",children:o.jsx("p",{className:"text-sm font-semibold truncate text-foreground/80",children:t.url})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("span",{className:"text-[10px] font-black uppercase text-muted-foreground tracking-widest pl-1",children:"Project Identifier"}),o.jsx("div",{className:"bg-muted/30 p-4 rounded-2xl border border-border/40 font-mono shadow-inner",children:o.jsx("p",{className:"text-sm font-semibold text-foreground/80",children:t.url.split("//")[1]?.split(".")[0]||"Unknown"})})]}),o.jsxs("div",{className:"md:col-span-2 space-y-2",children:[o.jsx("span",{className:"text-[10px] font-black uppercase text-muted-foreground tracking-widest pl-1",children:"Service Role Access (Masked)"}),o.jsxs("div",{className:"bg-muted/30 p-4 rounded-2xl border border-border/40 flex items-center justify-between shadow-inner",children:[o.jsxs("p",{className:"text-sm font-mono text-muted-foreground",children:[t.anonKey.slice(0,6),"...",t.anonKey.slice(-6)]}),o.jsx(Mt,{variant:"outline",className:"text-[9px] font-bold",children:"Standard Key"})]})]})]}):o.jsxs(jn,{className:"bg-amber-500/5 border-amber-500/20 text-amber-600 dark:text-amber-400 p-6 rounded-2xl shadow-sm",children:[o.jsx(Sn,{className:"w-5 h-5"}),o.jsx(Hm,{className:"font-bold mb-1",children:"Infrastructure Standby"}),o.jsx(_n,{className:"text-sm opacity-90",children:"The foundation has not been initialized. You must run the setup wizard to continue."})]})}),o.jsxs(Tu,{className:"bg-muted/20 p-8 flex gap-4 border-t",children:[o.jsxs(ae,{variant:t?"outline":"default",className:"flex-1 h-12 rounded-xl font-bold shadow-sm",onClick:s,children:[t?o.jsx(WC,{className:"w-4 h-4 mr-2"}):o.jsx(Ja,{className:"w-4 h-4 mr-2"}),t?"Run Setup Wizard":"Launch Initializer"]}),t&&o.jsx(ae,{variant:"ghost",size:"icon",className:"h-12 w-12 rounded-xl text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors",onClick:i,title:"Reset All Configuration",children:o.jsx(PC,{className:"w-5 h-5"})})]})]}),o.jsxs("div",{className:"space-y-6 pt-4",children:[o.jsxs("div",{className:"flex items-center gap-3 border-b pb-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-destructive/10 flex items-center justify-center text-destructive",children:o.jsx(Sn,{className:"w-6 h-6"})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-bold text-destructive",children:"Advanced Maintenance"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Destructive actions and system-level overrides."})]})]}),o.jsx(ht,{className:"border-destructive/20 bg-destructive/5 overflow-hidden shadow-sm",children:o.jsxs(xt,{className:"p-8",children:[o.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Fully resetting the foundation will purge all local storage cached parameters. This action is irreversible and will force a fresh bootstrap flow upon next launch."}),o.jsx(ae,{variant:"link",className:"px-0 text-destructive h-auto text-xs font-black uppercase tracking-widest mt-4 hover:no-underline hover:opacity-70 transition-opacity",onClick:i,children:"Wipe Local Foundation Buffer"})]})})]})]})}const tR={theme:"system",setTheme:()=>null},Zw=v.createContext(tR);function nR({children:t,defaultTheme:e="system",storageKey:s="vite-ui-theme"}){const[i,l]=v.useState(()=>localStorage.getItem(s)||e);v.useEffect(()=>{const d=window.document.documentElement;if(d.classList.remove("light","dark"),i==="system"){const h=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";d.classList.add(h);return}d.classList.add(i)},[i]);const u=v.useMemo(()=>({theme:i,setTheme:d=>{localStorage.setItem(s,d),l(d)}}),[i,s]);return o.jsx(Zw.Provider,{value:u,children:t})}const sR=()=>{const t=v.useContext(Zw);if(t===void 0)throw new Error("useTheme must be used within a ThemeProvider");return t};function e1(){const{setTheme:t,theme:e}=sR();return o.jsxs(ae,{variant:"ghost",size:"icon",onClick:()=>t(e==="dark"?"light":"dark"),className:"text-muted-foreground hover:bg-muted/60 transition-all duration-300 h-9 w-9 rounded-full",title:`Switch to ${e==="dark"?"light":"dark"} mode`,children:[e==="dark"?o.jsx(nA,{className:"h-[1.2rem] w-[1.2rem]"}):o.jsx(CC,{className:"h-[1.2rem] w-[1.2rem]"}),o.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}function fa(t,e,{checkForDefaultPrevented:s=!0}={}){return function(l){if(t?.(l),s===!1||!l.defaultPrevented)return e?.(l)}}function aR(t,e){const s=v.createContext(e),i=u=>{const{children:d,...h}=u,m=v.useMemo(()=>h,Object.values(h));return o.jsx(s.Provider,{value:m,children:d})};i.displayName=t+"Provider";function l(u){const d=v.useContext(s);if(d)return d;if(e!==void 0)return e;throw new Error(`\`${u}\` must be used within \`${t}\``)}return[i,l]}function iR(t,e=[]){let s=[];function i(u,d){const h=v.createContext(d),m=s.length;s=[...s,d];const p=x=>{const{scope:w,children:j,...T}=x,S=w?.[t]?.[m]||h,_=v.useMemo(()=>T,Object.values(T));return o.jsx(S.Provider,{value:_,children:j})};p.displayName=u+"Provider";function y(x,w){const j=w?.[t]?.[m]||h,T=v.useContext(j);if(T)return T;if(d!==void 0)return d;throw new Error(`\`${x}\` must be used within \`${u}\``)}return[p,y]}const l=()=>{const u=s.map(d=>v.createContext(d));return function(h){const m=h?.[t]||u;return v.useMemo(()=>({[`__scope${t}`]:{...h,[t]:m}}),[h,m])}};return l.scopeName=t,[i,rR(l,...e)]}function rR(...t){const e=t[0];if(t.length===1)return e;const s=()=>{const i=t.map(l=>({useScope:l(),scopeName:l.scopeName}));return function(u){const d=i.reduce((h,{useScope:m,scopeName:p})=>{const x=m(u)[`__scope${p}`];return{...h,...x}},{});return v.useMemo(()=>({[`__scope${e.scopeName}`]:d}),[d])}};return s.scopeName=e.scopeName,s}var qo=globalThis?.document?v.useLayoutEffect:()=>{},oR=Mm[" useId ".trim().toString()]||(()=>{}),lR=0;function mf(t){const[e,s]=v.useState(oR());return qo(()=>{s(i=>i??String(lR++))},[t]),t||(e?`radix-${e}`:"")}var cR=Mm[" useInsertionEffect ".trim().toString()]||qo;function uR({prop:t,defaultProp:e,onChange:s=()=>{},caller:i}){const[l,u,d]=dR({defaultProp:e,onChange:s}),h=t!==void 0,m=h?t:l;{const y=v.useRef(t!==void 0);v.useEffect(()=>{const x=y.current;x!==h&&console.warn(`${i} is changing from ${x?"controlled":"uncontrolled"} to ${h?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),y.current=h},[h,i])}const p=v.useCallback(y=>{if(h){const x=hR(y)?y(t):y;x!==t&&d.current?.(x)}else u(y)},[h,t,u,d]);return[m,p]}function dR({defaultProp:t,onChange:e}){const[s,i]=v.useState(t),l=v.useRef(s),u=v.useRef(e);return cR(()=>{u.current=e},[e]),v.useEffect(()=>{l.current!==s&&(u.current?.(s),l.current=s)},[s,l]),[s,i,u]}function hR(t){return typeof t=="function"}function fR(t){const e=mR(t),s=v.forwardRef((i,l)=>{const{children:u,...d}=i,h=v.Children.toArray(u),m=h.find(gR);if(m){const p=m.props.children,y=h.map(x=>x===m?v.Children.count(p)>1?v.Children.only(null):v.isValidElement(p)?p.props.children:null:x);return o.jsx(e,{...d,ref:l,children:v.isValidElement(p)?v.cloneElement(p,void 0,y):null})}return o.jsx(e,{...d,ref:l,children:u})});return s.displayName=`${t}.Slot`,s}function mR(t){const e=v.forwardRef((s,i)=>{const{children:l,...u}=s;if(v.isValidElement(l)){const d=vR(l),h=yR(u,l.props);return l.type!==v.Fragment&&(h.ref=i?Au(i,d):d),v.cloneElement(l,h)}return v.Children.count(l)>1?v.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var pR=Symbol("radix.slottable");function gR(t){return v.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===pR}function yR(t,e){const s={...e};for(const i in e){const l=t[i],u=e[i];/^on[A-Z]/.test(i)?l&&u?s[i]=(...h)=>{const m=u(...h);return l(...h),m}:l&&(s[i]=l):i==="style"?s[i]={...l,...u}:i==="className"&&(s[i]=[l,u].filter(Boolean).join(" "))}return{...t,...s}}function vR(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning;return s?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning,s?t.props.ref:t.props.ref||t.ref)}var xR=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Os=xR.reduce((t,e)=>{const s=fR(`Primitive.${e}`),i=v.forwardRef((l,u)=>{const{asChild:d,...h}=l,m=d?s:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(m,{...h,ref:u})});return i.displayName=`Primitive.${e}`,{...t,[e]:i}},{});function bR(t,e){t&&Ww.flushSync(()=>t.dispatchEvent(e))}function Ho(t){const e=v.useRef(t);return v.useEffect(()=>{e.current=t}),v.useMemo(()=>(...s)=>e.current?.(...s),[])}function wR(t,e=globalThis?.document){const s=Ho(t);v.useEffect(()=>{const i=l=>{l.key==="Escape"&&s(l)};return e.addEventListener("keydown",i,{capture:!0}),()=>e.removeEventListener("keydown",i,{capture:!0})},[s,e])}var SR="DismissableLayer",im="dismissableLayer.update",jR="dismissableLayer.pointerDownOutside",_R="dismissableLayer.focusOutside",b0,t1=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),n1=v.forwardRef((t,e)=>{const{disableOutsidePointerEvents:s=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:d,onDismiss:h,...m}=t,p=v.useContext(t1),[y,x]=v.useState(null),w=y?.ownerDocument??globalThis?.document,[,j]=v.useState({}),T=si(e,B=>x(B)),S=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),E=S.indexOf(_),C=y?S.indexOf(y):-1,A=p.layersWithOutsidePointerEventsDisabled.size>0,k=C>=E,M=ER(B=>{const R=B.target,I=[...p.branches].some(te=>te.contains(R));!k||I||(l?.(B),d?.(B),B.defaultPrevented||h?.())},w),P=kR(B=>{const R=B.target;[...p.branches].some(te=>te.contains(R))||(u?.(B),d?.(B),B.defaultPrevented||h?.())},w);return wR(B=>{C===p.layers.size-1&&(i?.(B),!B.defaultPrevented&&h&&(B.preventDefault(),h()))},w),v.useEffect(()=>{if(y)return s&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(b0=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),w0(),()=>{s&&p.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=b0)}},[y,w,s,p]),v.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),w0())},[y,p]),v.useEffect(()=>{const B=()=>j({});return document.addEventListener(im,B),()=>document.removeEventListener(im,B)},[]),o.jsx(Os.div,{...m,ref:T,style:{pointerEvents:A?k?"auto":"none":void 0,...t.style},onFocusCapture:fa(t.onFocusCapture,P.onFocusCapture),onBlurCapture:fa(t.onBlurCapture,P.onBlurCapture),onPointerDownCapture:fa(t.onPointerDownCapture,M.onPointerDownCapture)})});n1.displayName=SR;var NR="DismissableLayerBranch",TR=v.forwardRef((t,e)=>{const s=v.useContext(t1),i=v.useRef(null),l=si(e,i);return v.useEffect(()=>{const u=i.current;if(u)return s.branches.add(u),()=>{s.branches.delete(u)}},[s.branches]),o.jsx(Os.div,{...t,ref:l})});TR.displayName=NR;function ER(t,e=globalThis?.document){const s=Ho(t),i=v.useRef(!1),l=v.useRef(()=>{});return v.useEffect(()=>{const u=h=>{if(h.target&&!i.current){let m=function(){s1(jR,s,p,{discrete:!0})};const p={originalEvent:h};h.pointerType==="touch"?(e.removeEventListener("click",l.current),l.current=m,e.addEventListener("click",l.current,{once:!0})):m()}else e.removeEventListener("click",l.current);i.current=!1},d=window.setTimeout(()=>{e.addEventListener("pointerdown",u)},0);return()=>{window.clearTimeout(d),e.removeEventListener("pointerdown",u),e.removeEventListener("click",l.current)}},[e,s]),{onPointerDownCapture:()=>i.current=!0}}function kR(t,e=globalThis?.document){const s=Ho(t),i=v.useRef(!1);return v.useEffect(()=>{const l=u=>{u.target&&!i.current&&s1(_R,s,{originalEvent:u},{discrete:!1})};return e.addEventListener("focusin",l),()=>e.removeEventListener("focusin",l)},[e,s]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}function w0(){const t=new CustomEvent(im);document.dispatchEvent(t)}function s1(t,e,s,{discrete:i}){const l=s.originalEvent.target,u=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:s});e&&l.addEventListener(t,e,{once:!0}),i?bR(l,u):l.dispatchEvent(u)}var pf="focusScope.autoFocusOnMount",gf="focusScope.autoFocusOnUnmount",S0={bubbles:!1,cancelable:!0},CR="FocusScope",a1=v.forwardRef((t,e)=>{const{loop:s=!1,trapped:i=!1,onMountAutoFocus:l,onUnmountAutoFocus:u,...d}=t,[h,m]=v.useState(null),p=Ho(l),y=Ho(u),x=v.useRef(null),w=si(e,S=>m(S)),j=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(i){let S=function(A){if(j.paused||!h)return;const k=A.target;h.contains(k)?x.current=k:oa(x.current,{select:!0})},_=function(A){if(j.paused||!h)return;const k=A.relatedTarget;k!==null&&(h.contains(k)||oa(x.current,{select:!0}))},E=function(A){if(document.activeElement===document.body)for(const M of A)M.removedNodes.length>0&&oa(h)};document.addEventListener("focusin",S),document.addEventListener("focusout",_);const C=new MutationObserver(E);return h&&C.observe(h,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",_),C.disconnect()}}},[i,h,j.paused]),v.useEffect(()=>{if(h){_0.add(j);const S=document.activeElement;if(!h.contains(S)){const E=new CustomEvent(pf,S0);h.addEventListener(pf,p),h.dispatchEvent(E),E.defaultPrevented||(AR(PR(i1(h)),{select:!0}),document.activeElement===S&&oa(h))}return()=>{h.removeEventListener(pf,p),setTimeout(()=>{const E=new CustomEvent(gf,S0);h.addEventListener(gf,y),h.dispatchEvent(E),E.defaultPrevented||oa(S??document.body,{select:!0}),h.removeEventListener(gf,y),_0.remove(j)},0)}}},[h,p,y,j]);const T=v.useCallback(S=>{if(!s&&!i||j.paused)return;const _=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,E=document.activeElement;if(_&&E){const C=S.currentTarget,[A,k]=RR(C);A&&k?!S.shiftKey&&E===k?(S.preventDefault(),s&&oa(A,{select:!0})):S.shiftKey&&E===A&&(S.preventDefault(),s&&oa(k,{select:!0})):E===C&&S.preventDefault()}},[s,i,j.paused]);return o.jsx(Os.div,{tabIndex:-1,...d,ref:w,onKeyDown:T})});a1.displayName=CR;function AR(t,{select:e=!1}={}){const s=document.activeElement;for(const i of t)if(oa(i,{select:e}),document.activeElement!==s)return}function RR(t){const e=i1(t),s=j0(e,t),i=j0(e.reverse(),t);return[s,i]}function i1(t){const e=[],s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>{const l=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||l?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;s.nextNode();)e.push(s.currentNode);return e}function j0(t,e){for(const s of t)if(!OR(s,{upTo:e}))return s}function OR(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function MR(t){return t instanceof HTMLInputElement&&"select"in t}function oa(t,{select:e=!1}={}){if(t&&t.focus){const s=document.activeElement;t.focus({preventScroll:!0}),t!==s&&MR(t)&&e&&t.select()}}var _0=DR();function DR(){let t=[];return{add(e){const s=t[0];e!==s&&s?.pause(),t=N0(t,e),t.unshift(e)},remove(e){t=N0(t,e),t[0]?.resume()}}}function N0(t,e){const s=[...t],i=s.indexOf(e);return i!==-1&&s.splice(i,1),s}function PR(t){return t.filter(e=>e.tagName!=="A")}var zR="Portal",r1=v.forwardRef((t,e)=>{const{container:s,...i}=t,[l,u]=v.useState(!1);qo(()=>u(!0),[]);const d=s||l&&globalThis?.document?.body;return d?VA.createPortal(o.jsx(Os.div,{...i,ref:e}),d):null});r1.displayName=zR;function LR(t,e){return v.useReducer((s,i)=>e[s][i]??s,t)}var Ru=t=>{const{present:e,children:s}=t,i=UR(e),l=typeof s=="function"?s({present:i.isPresent}):v.Children.only(s),u=si(i.ref,BR(l));return typeof s=="function"||i.isPresent?v.cloneElement(l,{ref:u}):null};Ru.displayName="Presence";function UR(t){const[e,s]=v.useState(),i=v.useRef(null),l=v.useRef(t),u=v.useRef("none"),d=t?"mounted":"unmounted",[h,m]=LR(d,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const p=Lc(i.current);u.current=h==="mounted"?p:"none"},[h]),qo(()=>{const p=i.current,y=l.current;if(y!==t){const w=u.current,j=Lc(p);t?m("MOUNT"):j==="none"||p?.display==="none"?m("UNMOUNT"):m(y&&w!==j?"ANIMATION_OUT":"UNMOUNT"),l.current=t}},[t,m]),qo(()=>{if(e){let p;const y=e.ownerDocument.defaultView??window,x=j=>{const S=Lc(i.current).includes(CSS.escape(j.animationName));if(j.target===e&&S&&(m("ANIMATION_END"),!l.current)){const _=e.style.animationFillMode;e.style.animationFillMode="forwards",p=y.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=_)})}},w=j=>{j.target===e&&(u.current=Lc(i.current))};return e.addEventListener("animationstart",w),e.addEventListener("animationcancel",x),e.addEventListener("animationend",x),()=>{y.clearTimeout(p),e.removeEventListener("animationstart",w),e.removeEventListener("animationcancel",x),e.removeEventListener("animationend",x)}}else m("ANIMATION_END")},[e,m]),{isPresent:["mounted","unmountSuspended"].includes(h),ref:v.useCallback(p=>{i.current=p?getComputedStyle(p):null,s(p)},[])}}function Lc(t){return t?.animationName||"none"}function BR(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning;return s?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,s=e&&"isReactWarning"in e&&e.isReactWarning,s?t.props.ref:t.props.ref||t.ref)}var yf=0;function VR(){v.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??T0()),document.body.insertAdjacentElement("beforeend",t[1]??T0()),yf++,()=>{yf===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),yf--}},[])}function T0(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Yc="right-scroll-bar-position",Xc="width-before-scroll-bar",IR="with-scroll-bars-hidden",$R="--removed-body-scroll-bar-size";function vf(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function qR(t,e){var s=v.useState(function(){return{value:t,callback:e,facade:{get current(){return s.value},set current(i){var l=s.value;l!==i&&(s.value=i,s.callback(i,l))}}}})[0];return s.callback=e,s.facade}var HR=typeof window<"u"?v.useLayoutEffect:v.useEffect,E0=new WeakMap;function GR(t,e){var s=qR(null,function(i){return t.forEach(function(l){return vf(l,i)})});return HR(function(){var i=E0.get(s);if(i){var l=new Set(i),u=new Set(t),d=s.current;l.forEach(function(h){u.has(h)||vf(h,null)}),u.forEach(function(h){l.has(h)||vf(h,d)})}E0.set(s,t)},[t]),s}function FR(t){return t}function KR(t,e){e===void 0&&(e=FR);var s=[],i=!1,l={read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return s.length?s[s.length-1]:t},useMedium:function(u){var d=e(u,i);return s.push(d),function(){s=s.filter(function(h){return h!==d})}},assignSyncMedium:function(u){for(i=!0;s.length;){var d=s;s=[],d.forEach(u)}s={push:function(h){return u(h)},filter:function(){return s}}},assignMedium:function(u){i=!0;var d=[];if(s.length){var h=s;s=[],h.forEach(u),d=s}var m=function(){var y=d;d=[],y.forEach(u)},p=function(){return Promise.resolve().then(m)};p(),s={push:function(y){d.push(y),p()},filter:function(y){return d=d.filter(y),s}}}};return l}function YR(t){t===void 0&&(t={});var e=KR(null);return e.options=ss({async:!0,ssr:!1},t),e}var o1=function(t){var e=t.sideCar,s=gr(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=e.read();if(!i)throw new Error("Sidecar medium not found");return v.createElement(i,ss({},s))};o1.isSideCarExport=!0;function XR(t,e){return t.useMedium(e),o1}var l1=YR(),xf=function(){},Ou=v.forwardRef(function(t,e){var s=v.useRef(null),i=v.useState({onScrollCapture:xf,onWheelCapture:xf,onTouchMoveCapture:xf}),l=i[0],u=i[1],d=t.forwardProps,h=t.children,m=t.className,p=t.removeScrollBar,y=t.enabled,x=t.shards,w=t.sideCar,j=t.noRelative,T=t.noIsolation,S=t.inert,_=t.allowPinchZoom,E=t.as,C=E===void 0?"div":E,A=t.gapMode,k=gr(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),M=w,P=GR([s,e]),B=ss(ss({},k),l);return v.createElement(v.Fragment,null,y&&v.createElement(M,{sideCar:l1,removeScrollBar:p,shards:x,noRelative:j,noIsolation:T,inert:S,setCallbacks:u,allowPinchZoom:!!_,lockRef:s,gapMode:A}),d?v.cloneElement(v.Children.only(h),ss(ss({},B),{ref:P})):v.createElement(C,ss({},B,{className:m,ref:P}),h))});Ou.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ou.classNames={fullWidth:Xc,zeroRight:Yc};var WR=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function JR(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=WR();return e&&t.setAttribute("nonce",e),t}function QR(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function ZR(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var eO=function(){var t=0,e=null;return{add:function(s){t==0&&(e=JR())&&(QR(e,s),ZR(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},tO=function(){var t=eO();return function(e,s){v.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&s])}},c1=function(){var t=tO(),e=function(s){var i=s.styles,l=s.dynamic;return t(i,l),null};return e},nO={left:0,top:0,right:0,gap:0},bf=function(t){return parseInt(t||"",10)||0},sO=function(t){var e=window.getComputedStyle(document.body),s=e[t==="padding"?"paddingLeft":"marginLeft"],i=e[t==="padding"?"paddingTop":"marginTop"],l=e[t==="padding"?"paddingRight":"marginRight"];return[bf(s),bf(i),bf(l)]},aO=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return nO;var e=sO(t),s=document.documentElement.clientWidth,i=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,i-s+e[2]-e[0])}},iO=c1(),cr="data-scroll-locked",rO=function(t,e,s,i){var l=t.left,u=t.top,d=t.right,h=t.gap;return s===void 0&&(s="margin"),`
52
52
  .`.concat(IR,` {
53
53
  overflow: hidden `).concat(i,`;
54
54
  padding-right: `).concat(h,"px ").concat(i,`;
@@ -109,5 +109,5 @@ For more information, see https://radix-ui.com/primitives/docs/components/${e.do
109
109
  bg-violet-500 hover:bg-violet-600 text-white`,children:"Apply Suggestion"}),o.jsx(ae,{size:"sm",variant:"outline",onClick:()=>B(null),className:"h-8 px-3 rounded-xl",children:"Discard"})]})]})]})]}),o.jsxs(ht,{children:[o.jsxs(zt,{children:[o.jsxs(Lt,{className:"flex items-center gap-2",children:[o.jsx(Pw,{className:"w-5 h-5 text-violet-500"}),"Extraction Context"]}),o.jsx(wn,{children:"Describe the kinds of documents you typically process. This context is injected directly into the extraction prompt, helping the model specialise for your workflow."})]}),o.jsx(xt,{children:o.jsx("textarea",{className:`w-full min-h-[96px] rounded-md border bg-background px-3 py-2 text-sm resize-y
110
110
  focus:outline-none focus:ring-2 focus:ring-ring placeholder:text-muted-foreground`,placeholder:'e.g. "I primarily process SaaS vendor invoices and software contracts. Documents are in English and French. Frequent vendors include Stripe, AWS, and GitHub."',value:d,onChange:q=>h(q.target.value)})})]}),o.jsxs(ht,{children:[o.jsxs(zt,{children:[o.jsx(Lt,{className:"text-base",children:"Default Fields"}),o.jsx(wn,{children:"Built-in fields extracted from every document. Toggle to enable or disable. Edit the description to give the model a better hint for your documents."})]}),o.jsx(xt,{className:"space-y-3",children:le.map(q=>o.jsxs("div",{className:"flex items-start gap-3 group",children:[o.jsx("button",{type:"button",onClick:()=>V(q.key),className:`mt-0.5 flex-shrink-0 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors
111
111
  ${q.enabled?"bg-violet-500 border-violet-500":"border-muted-foreground/40 bg-background"}`,children:q.enabled&&o.jsx(as,{className:"w-3 h-3 text-white"})}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("code",{className:"text-xs font-mono bg-muted px-1.5 py-0.5 rounded",children:q.key}),o.jsx(Mt,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:q.type})]}),o.jsx(_e,{className:"h-7 text-xs",value:q.description,disabled:!q.enabled,onChange:pe=>F(q.key,pe.target.value)})]})]},q.key))})]}),o.jsxs(ht,{children:[o.jsx(zt,{children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx(Lt,{className:"text-base",children:"Custom Fields"}),o.jsx(wn,{className:"mt-1",children:"Add fields specific to your workflow — project codes, contract types, department names, or any entity your documents carry."})]}),o.jsxs(ae,{variant:"outline",size:"sm",onClick:J,className:"gap-1.5",children:[o.jsx(Ja,{className:"w-3.5 h-3.5"}),"Add Field"]})]})}),de.length>0&&o.jsx(xt,{className:"space-y-4",children:m.map((q,pe)=>q.is_default?null:o.jsxs("div",{className:"grid grid-cols-[1fr_120px_1fr_32px] gap-2 items-start",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"Key"}),o.jsx(_e,{className:"h-8 text-xs font-mono",placeholder:"e.g. project_code",value:q.key,onChange:oe=>ge(pe,{key:oe.target.value.toLowerCase().replace(/\s+/g,"_")})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"Type"}),o.jsx("select",{className:"w-full h-8 text-xs border rounded-md px-2 bg-background",value:q.type,onChange:oe=>ge(pe,{type:oe.target.value}),children:T6.map(oe=>o.jsx("option",{value:oe,children:oe},oe))})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"Description / hint for the model"}),o.jsx(_e,{className:"h-8 text-xs",placeholder:"What this field contains",value:q.description,onChange:oe=>ge(pe,{description:oe.target.value})})]}),o.jsx("button",{type:"button",onClick:()=>ne(pe),className:"mt-6 p-1 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors",children:o.jsx(el,{className:"w-3.5 h-3.5"})})]},pe))})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("button",{type:"button",onClick:T?()=>S(!1):se,className:"flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[o.jsx(pC,{className:"w-3.5 h-3.5"}),"Version history",y!==null&&o.jsxs(Mt,{variant:"secondary",className:"text-[10px] px-1.5 py-0 ml-1",children:["v",y," active"]}),T?o.jsx(lu,{className:"w-3 h-3"}):o.jsx(Bo,{className:"w-3 h-3"})]}),o.jsxs(ae,{onClick:D,disabled:l,className:"gap-2",children:[l?o.jsx(cn,{size:"sm"}):o.jsx(as,{className:"w-4 h-4"}),"Save & Activate"]})]}),T&&o.jsx(ht,{children:o.jsx(xt,{className:"pt-4 space-y-2",children:w.length===0?o.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No saved versions yet"}):w.map(q=>o.jsxs("div",{className:"flex items-center justify-between py-2 px-3 rounded-lg border bg-muted/30",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("span",{className:"text-sm font-mono font-medium",children:["v",q.version]}),q.is_active&&o.jsx(Mt,{className:"text-[10px] px-1.5 py-0 bg-violet-500 text-white",children:"active"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(q.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:["· ",q.fields.filter(pe=>pe.enabled).length," fields",q.context?" · context set":""]})]}),!q.is_active&&o.jsx(ae,{variant:"outline",size:"sm",className:"h-6 text-xs px-2",onClick:()=>L(q.id,q.version),children:"Activate"})]},q.id))})})]})}const Ep=v.createContext(null),kj=v.forwardRef(({className:t,defaultValue:e,value:s,onValueChange:i,...l},u)=>{const[d,h]=v.useState(e||""),m=s!==void 0?s:d,p=v.useCallback(y=>{i&&i(y),s===void 0&&h(y)},[i,s]);return o.jsx(Ep.Provider,{value:{value:m,onValueChange:p},children:o.jsx("div",{ref:u,className:t,...l})})});kj.displayName="Tabs";const Cj=v.forwardRef(({className:t,...e},s)=>o.jsx("div",{ref:s,className:ve("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));Cj.displayName="TabsList";const jo=v.forwardRef(({className:t,value:e,onClick:s,...i},l)=>{const u=v.useContext(Ep);if(!u)throw new Error("TabsTrigger must be used within Tabs");const d=u.value===e;return o.jsx("button",{ref:l,type:"button",role:"tab","aria-selected":d,"data-state":d?"active":"inactive",className:ve("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),onClick:h=>{u.onValueChange(e),s?.(h)},...i})});jo.displayName="TabsTrigger";const _o=v.forwardRef(({className:t,value:e,...s},i)=>{const l=v.useContext(Ep);if(!l)throw new Error("TabsContent must be used within Tabs");return l.value!==e?null:o.jsx("div",{ref:i,role:"tabpanel","data-state":"active",className:ve("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s})});_o.displayName="TabsContent";const $a="realtimexai";function k6(){const{state:t,actions:e}=ol(),{t:s}=wr(),[i,l]=v.useState(!1),[u,d]=v.useState(!1),[h,m]=v.useState({});m6({system_instruction:s("config.agent.systemInstruction"),data:{accounts_count:t.accounts.length,connected_providers:t.accounts.map(se=>se.provider),rules_count:t.rules.length,active_rules:t.rules.filter(se=>se.is_enabled).map(se=>se.name),current_settings:{llm_provider:h.llm_provider,llm_model:h.llm_model,ingestion_llm_provider:h.ingestion_llm_provider,ingestion_llm_model:h.ingestion_llm_model}}});const[p,y]=v.useState([]),[x,w]=v.useState([]);v.useEffect(()=>{(async()=>{try{const F=await Ee.getChatProviders();F.data&&y(F.data.providers||[])}catch(F){console.error(F)}})(),(async()=>{try{const F=await Ee.getEmbedProviders();F.data&&w(F.data.providers||[])}catch(F){console.error(F)}})()},[s]);const T=p.find(se=>se.provider===(h.llm_provider||$a))?.models||[],S=h.ingestion_llm_provider||h.llm_provider||$a,E=p.find(se=>se.provider===S)?.models||[],A=x.find(se=>se.provider===(h.embedding_provider||$a))?.models||[],k=v.useMemo(()=>!h.llm_model||T.some(V=>V.id===h.llm_model)?T:[{id:h.llm_model,name:`${h.llm_model} (saved)`},...T],[T,h.llm_model]),M=v.useMemo(()=>!h.llm_provider||h.llm_provider===$a||p.some(V=>V.provider===h.llm_provider)?p:[{provider:h.llm_provider,name:`${h.llm_provider} (saved)`,models:[]},...p],[p,h.llm_provider]),P=v.useMemo(()=>{const se=h.ingestion_llm_model||h.llm_model;return!se||E.some(F=>F.id===se)?E:[{id:se,name:`${se} (saved)`},...E]},[E,h.ingestion_llm_model,h.llm_model]),B=v.useMemo(()=>!h.ingestion_llm_provider||h.ingestion_llm_provider===$a||p.some(V=>V.provider===h.ingestion_llm_provider)?p:[{provider:h.ingestion_llm_provider,name:`${h.ingestion_llm_provider} (saved)`,models:[]},...p],[p,h.ingestion_llm_provider]),R=v.useMemo(()=>!h.embedding_model||A.some(V=>V.id===h.embedding_model)?A:[{id:h.embedding_model,name:`${h.embedding_model} (saved)`},...A],[A,h.embedding_model]),I=v.useMemo(()=>!h.embedding_provider||h.embedding_provider===$a||x.some(V=>V.provider===h.embedding_provider)?x:[{provider:h.embedding_provider,name:`${h.embedding_provider} (saved)`,models:[]},...x],[x,h.embedding_provider]),te=se=>{const V=p.find(F=>F.provider===se);m(F=>({...F,llm_provider:se,llm_model:V?.models?.[0]?.id||""}))},ie=se=>{const V=x.find(F=>F.provider===se);m(F=>({...F,embedding_provider:se,embedding_model:V?.models?.[0]?.id||""}))},fe=se=>{const V=p.find(F=>F.provider===se);m(F=>({...F,ingestion_llm_provider:se,ingestion_llm_model:V?.models?.[0]?.id||""}))},Ne=async()=>{d(!0);try{const se=await Ee.testLlm({llm_provider:h.llm_provider||void 0,llm_model:h.llm_model||void 0});se.data?.success?ue.success(se.data.message):ue.error(s("config.toast.connectionFailed"))}catch{ue.error(s("config.toast.connectionFailed"))}finally{d(!1)}};v.useEffect(()=>{e.fetchAccounts(),e.fetchRules(),e.fetchSettings()},[]),v.useEffect(()=>{t.settings&&m(t.settings)},[t.settings]);const ye=async()=>{l(!0);const se=await e.updateSettings(h);l(!1),se&&ue.success(s("config.toast.settingsSaved"))};return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-6 animate-in fade-in duration-500 flex flex-col h-full",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{children:[o.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Configuration"}),o.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage your connected integrations and AI providers."})]})}),o.jsxs(kj,{defaultValue:"mail",className:"w-full",children:[o.jsxs(Cj,{className:"grid w-full grid-cols-4 max-w-lg h-12",children:[o.jsx(jo,{value:"mail",className:"h-10",children:"Mail"}),o.jsx(jo,{value:"storage",className:"h-10",children:"Storage"}),o.jsx(jo,{value:"intelligence",className:"h-10",children:"Intelligence"}),o.jsx(jo,{value:"baseline",className:"h-10",children:"Baseline"})]}),o.jsxs("div",{className:"mt-8",children:[o.jsx(_o,{value:"mail",className:"m-0 border-none p-0 outline-none",children:o.jsx(g6,{localSettings:h,setLocalSettings:m,handleSaveSettings:ye,savingSettings:i})}),o.jsx(_o,{value:"storage",className:"m-0 border-none p-0 outline-none",children:o.jsx(_6,{})}),o.jsx(_o,{value:"intelligence",className:"m-0 border-none p-0 outline-none",children:o.jsx(j6,{localSettings:h,setLocalSettings:m,handleSaveSettings:ye,savingSettings:i,handleTestConnection:Ne,testingLlm:u,providersWithSaved:M,modelsWithSaved:k,embedProvidersWithSaved:I,embedModelsWithSaved:R,ingestionProvidersWithSaved:B,ingestionModelsWithSaved:P,handleProviderChange:te,handleEmbedProviderChange:ie,handleIngestionProviderChange:fe,DEFAULT_PROVIDER:$a})}),o.jsx(_o,{value:"baseline",className:"m-0 border-none p-0 outline-none",children:o.jsx(E6,{})})]})]})]})}function C6({status:t,onSnooze:e,onOpenModal:s}){const[i,l]=v.useState(!1),[u,d]=v.useState(!1),h=p=>{const y=new Date(Date.now()+p*60*60*1e3);e?.(y),ue.success(`Reminder snoozed until ${y.toLocaleTimeString()}`)},m=["Enhanced TTS voice support (Piper, Supertonic)","Real-time audio streaming infrastructure","Improved AI model provider resolution"];return i?o.jsx("div",{className:"fixed top-24 left-1/2 -translate-x-1/2 z-[60] animate-in slide-in-from-top-5",children:o.jsxs("button",{onClick:()=>l(!1),className:"flex items-center gap-2 px-4 py-2 bg-amber-500 text-amber-950 rounded-full shadow-2xl shadow-amber-500/20 hover:scale-105 active:scale-95 transition-all text-[11px] font-black uppercase tracking-widest border border-amber-400/50 backdrop-blur-md",children:[o.jsx(Cs,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:"System Update Available"})]})}):o.jsx("div",{className:"fixed top-0 left-0 right-0 z-[60] animate-in slide-in-from-top-10 duration-700",children:o.jsxs("div",{className:"bg-amber-500 text-amber-950 px-6 py-4 shadow-2xl border-b border-amber-400/50 backdrop-blur-xl relative overflow-hidden",children:[o.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2 blur-3xl pointer-events-none"}),o.jsx("div",{className:"max-w-5xl mx-auto relative",children:o.jsxs("div",{className:"flex items-start gap-6",children:[o.jsx("div",{className:"w-12 h-12 rounded-2xl bg-amber-950/10 flex items-center justify-center shrink-0",children:o.jsx(Gw,{className:"h-6 w-6"})}),o.jsxs("div",{className:"flex-1 space-y-3",children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"text-lg font-black tracking-tight flex items-center gap-2",children:["Foundational Update Required",o.jsxs("span",{className:"text-[10px] px-2 py-0.5 bg-amber-950/10 rounded-full border border-amber-950/20 uppercase tracking-widest font-black",children:["v",t.appVersion]})]}),o.jsx("p",{className:"text-sm font-medium opacity-80 mt-1 max-w-2xl leading-relaxed",children:"New architecture components detected. Migration is necessary to enable real-time audio streaming and enhanced AI provider resolution."})]}),o.jsx(ae,{size:"icon",variant:"ghost",className:"h-8 w-8 text-amber-950 hover:bg-amber-950/10 rounded-full shrink-0",onClick:()=>l(!0),children:o.jsx($w,{className:"h-4 w-4"})})]}),u&&o.jsxs("div",{className:"bg-amber-950/5 rounded-2xl p-4 border border-amber-950/10 animate-in fade-in slide-in-from-top-2",children:[o.jsx("p",{className:"text-[10px] font-black uppercase tracking-widest opacity-60 mb-3",children:"Protocol Improvements:"}),o.jsx("ul",{className:"grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-2",children:m.map((p,y)=>o.jsxs("li",{className:"text-xs flex items-center gap-2 font-bold",children:[o.jsx("div",{className:"w-1 h-1 rounded-full bg-amber-950/40"}),p]},y))})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-3 pt-1",children:[o.jsx(ae,{size:"sm",className:"h-9 px-6 bg-amber-950 text-amber-50 hover:bg-black rounded-full font-black text-[10px] uppercase tracking-[0.2em] shadow-xl shadow-amber-950/20 active:scale-95 transition-all",onClick:s,children:"Apply Update Now"}),o.jsx("div",{className:"h-4 w-px bg-amber-950/20 hidden sm:block mx-1"}),o.jsxs(ae,{size:"sm",variant:"ghost",className:"h-9 text-amber-950 font-black text-[10px] uppercase tracking-widest hover:bg-amber-950/10 rounded-full",onClick:()=>h(1),children:[o.jsx(Qo,{className:"h-3.5 w-3.5 mr-2 opacity-60"}),"Snooze 1h"]}),o.jsxs(ae,{size:"sm",variant:"ghost",className:"h-9 text-amber-950 font-black text-[10px] uppercase tracking-widest hover:bg-amber-950/10 rounded-full",onClick:()=>h(24),children:[o.jsx(zw,{className:"h-3.5 w-3.5 mr-2 opacity-60"}),"Tomorrow"]}),o.jsxs(ae,{size:"sm",variant:"ghost",className:"h-9 text-amber-950 font-black text-[10px] uppercase tracking-widest hover:bg-amber-950/10 rounded-full ml-auto",onClick:()=>d(!u),children:[u?o.jsx(lu,{className:"h-4 w-4"}):o.jsx(Bo,{className:"h-4 w-4"}),o.jsx("span",{className:"ml-2",children:u?"Hide Details":"Inspect Protocol"})]})]})]})]})})]})})}function A6({open:t,onOpenChange:e,status:s,onSnooze:i}){const l=$o(),u=S=>{const _=new Date(Date.now()+S*60*60*1e3);i?.(_),ue.success(`Reminder snoozed until ${_.toLocaleTimeString()}`),e(!1)},[d,h]=v.useState(!1),[m,p]=v.useState([]),[y,x]=v.useState(""),w=v.useRef(null),j=v.useMemo(()=>{const S=l?.url;if(!S)return"";try{return new URL(S).hostname.split(".")[0]||""}catch{return""}},[l?.url]);v.useEffect(()=>{w.current&&w.current.scrollIntoView({behavior:"smooth"})},[m]);const T=async()=>{if(!j){ue.error("Foundation Error: Missing Project ID");return}if(!y){ue.error("Security Error: Provide a Supabase Access Token.");return}h(!0),p(["[System] Initializing migration protocol...","[Auth] Verifying project credentials..."]);try{const S=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:j,accessToken:y})});if(!S.ok)throw new Error(`Migration engine failed: ${S.status}`);const _=S.body?.getReader();if(!_)throw new Error("Failed to initialize log stream.");const E=new TextDecoder;let C="",A=!1;for(;;){const{done:k,value:M}=await _.read();if(k)break;C+=E.decode(M,{stream:!0});const P=C.split(`
112
- `);C=P.pop()||"";for(const B of P){const R=B.trim();if(!(!R||!R.startsWith("data: ")))try{const I=JSON.parse(R.substring(6));I.type==="done"?I.data==="success"&&(A=!0):I.data&&p(te=>[...te,I.data])}catch{}}}if(A)p(k=>[...k,"","═".repeat(50),"✅ FOUNDATION UPDATED","","✓ Database schema synchronized","✓ API contracts verified","","System will reload to apply changes...","═".repeat(50)]),setTimeout(()=>{window.location.reload()},2e3);else throw new Error("Migration completed with errors.")}catch(S){console.error(S),p(_=>[..._,"",`❌ FATAL ERROR: ${S instanceof Error?S.message:String(S)}`]),ue.error("Migration interrupted. Consult system logs.")}finally{h(!1)}};return o.jsx(ei,{open:t,onOpenChange:S=>!d&&e(S),children:o.jsx(ti,{className:"max-h-[90vh] sm:max-w-4xl overflow-y-auto border-none bg-background/95 backdrop-blur-2xl shadow-2xl p-0 gap-0 selection:bg-primary/20",children:o.jsxs("div",{className:"bg-gradient-to-br from-primary/5 via-transparent to-transparent",children:[o.jsx(fr,{className:"p-8 pb-4",children:o.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[o.jsx("div",{className:"w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center",children:o.jsx(hu,{className:"h-6 w-6 text-primary"})}),o.jsxs("div",{children:[o.jsx(mr,{className:"text-2xl font-black tracking-tight",children:"Database Setup Required"}),o.jsxs(tl,{className:"text-xs font-bold uppercase tracking-[0.2em] opacity-60",children:["Foundational Registry Sync • ",s.appVersion]})]})]})}),o.jsxs("div",{className:"px-8 pb-8 space-y-6",children:[o.jsxs(jn,{className:"bg-muted/40 border-none rounded-2xl p-4",children:[o.jsx(Im,{className:"h-4 w-4 text-primary"}),o.jsxs(_n,{className:"text-xs font-medium leading-relaxed",children:["Your application requires a database schema update to enable new features like ",o.jsx("strong",{children:"Enhanced TTS Engine"})," and ",o.jsx("strong",{children:"Real-time Intelligence Streaming"}),". Existing data remains untouched."]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsx("div",{className:"space-y-4",children:o.jsxs("div",{className:"rounded-2xl border bg-card/50 shadow-sm p-6 space-y-4",children:[o.jsx("h3",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground",children:"Security Credentials"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"project-id",className:"text-[10px] uppercase tracking-widest font-black opacity-60",children:"Project Identity"}),o.jsx(_e,{id:"project-id",value:j,disabled:!0,readOnly:!0,className:"h-10 bg-muted/50 border-none font-mono text-xs rounded-xl"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx(Je,{htmlFor:"access-token",className:"text-[10px] uppercase tracking-widest font-black opacity-60",children:"Personal Access Token"}),o.jsxs("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-[10px] font-black tracking-widest text-primary hover:underline flex items-center gap-1",children:["GENERATE ",o.jsx(Uw,{className:"h-2.5 w-2.5"})]})]}),o.jsx(_e,{id:"access-token",type:"password",placeholder:"sbp_...",value:y,onChange:S=>x(S.target.value),disabled:d,className:"h-10 bg-background border-border/40 focus:ring-primary/20 rounded-xl font-mono text-xs"})]}),o.jsx(ae,{onClick:T,disabled:d||!y,className:"w-full h-11 rounded-xl bg-primary text-primary-foreground font-black text-[10px] uppercase tracking-[0.2em] shadow-lg shadow-primary/20 hover:scale-[1.02] active:scale-[0.98] transition-all",children:d?o.jsxs(o.Fragment,{children:[o.jsx(rt,{className:"mr-2 h-4 w-4 animate-spin"}),"Deploying..."]}):o.jsxs(o.Fragment,{children:[o.jsx(ya,{className:"mr-2 h-4 w-4"}),"Initialize Protocol"]})})]})]})}),o.jsxs("div",{className:"flex flex-col rounded-2xl border bg-zinc-950/95 text-zinc-400 font-mono text-[11px] p-5 shadow-inner min-h-[300px] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-4 shrink-0",children:[o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-red-500/20"}),o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-amber-500/20"}),o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-emerald-500/20"})]}),o.jsx("span",{className:"text-[9px] font-black uppercase tracking-widest opacity-40 ml-2",children:"Foundation Terminal"})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:[m.length===0?o.jsxs("div",{className:"text-zinc-700 italic flex flex-col items-center justify-center h-full opacity-50",children:[o.jsx(Io,{className:"h-8 w-8 mb-2"}),o.jsx("span",{children:"Awaiting synchronization..."})]}):m.map((S,_)=>o.jsxs("div",{className:ve("mb-1.5 leading-relaxed break-words",S.includes("✅")||S.includes("success")?"text-emerald-400":S.includes("❌")||S.includes("Error")?"text-red-400 font-bold":S.includes("🚀")||S.includes("[System]")?"text-primary":""),children:[o.jsx("span",{className:"opacity-30 mr-2",children:_+1}),S]},_)),o.jsx("div",{ref:w})]})]})]})]}),o.jsx(nr,{className:"p-8 pt-0 flex-col sm:flex-row gap-3",children:o.jsxs("div",{className:"flex gap-3 w-full",children:[o.jsxs(ae,{type:"button",variant:"secondary",onClick:()=>u(1),disabled:d,className:"flex-1 h-11 rounded-xl font-black text-[10px] uppercase tracking-widest",children:[o.jsx(Qo,{className:"h-4 w-4 mr-2 opacity-60"}),"Snooze 1h"]}),o.jsxs(ae,{type:"button",variant:"secondary",onClick:()=>u(24),disabled:d,className:"flex-1 h-11 rounded-xl font-black text-[10px] uppercase tracking-widest",children:[o.jsx(zw,{className:"h-4 w-4 mr-2 opacity-60"}),"Tomorrow"]})]})})]})})})}const R6=[{id:"bay-area-utilities",name:"Bay Area Utilities",description:"PG&E, Recology, EBMUD, and SCE bill handling",policies:4,tags:["utilities","california"]},{id:"freelancer-tax",name:"Freelancer Tax Pack",description:"1099-NEC, W-9, invoices, and estimated taxes",policies:6,tags:["finance","tax"]},{id:"medical-records",name:"Medical Records",description:"EOB, lab results, prescription receipts",policies:5,tags:["health","insurance"]},{id:"legal-docs",name:"Legal Documents",description:"Contracts, notices, deeds, and court documents",policies:3,tags:["legal","priority"]}];function O6({initialCompose:t,onInitialConsumed:e}){const[s,i]=v.useState([]),[l,u]=v.useState(!0),[d,h]=v.useState(""),[m,p]=v.useState(!1),[y,x]=v.useState(null),[w,j]=v.useState(!1),[T,S]=v.useState(!1),[_,E]=v.useState(null),[C,A]=v.useState("policies"),[k,M]=v.useState([]),[P,B]=v.useState(""),[R,I]=v.useState(""),[te,ie]=v.useState(null),[fe,Ne]=v.useState(null),[ye,se]=v.useState(null),[V,F]=v.useState(!1),[J,ge]=v.useState({name:"",description:"",keywords:"",matchStrategy:"ANY",actions:[{type:"copy",destination:"",filename:"",columns:[],spreadsheet_id:"",range:""}],tags:"",priority:100}),[ne,D]=v.useState(!1),L=v.useCallback(async()=>{u(!0);const U=await Ee.getPolicies?.(te);U?.data?.policies&&i(U.data.policies),u(!1)},[te]),W=v.useCallback(async()=>{try{const re=(await Ee.getSDKChatProviders?.())?.data?.providers??[];M(re),re.length>0&&!P&&(B(re[0].provider),I(re[0].models?.[0]?.id??""))}catch{}},[P]);v.useEffect(()=>{const U=un();U&&U.auth.getSession().then(({data:re})=>{ie(re.session?.access_token??null)})},[]),v.useEffect(()=>{L(),W()},[L,W]),v.useEffect(()=>{t&&(h(t),e?.())},[t,e]);const ee=async()=>{if(d.trim()){p(!0),x(null);try{const U=await Ee.synthesizePolicy?.({description:d,provider:P||void 0,model:R||void 0},te);if(U?.data?.policy){x(U.data.policy),j(!1);const re=U.data.warning;re?ue.warning(re):ue.success("Policy synthesized! Review and save below.")}else ue.error(U?.data?.error??"Synthesis failed.")}catch{ue.error("LLM synthesis failed.")}finally{p(!1)}}},le=async U=>{S(!0);try{await Ee.savePolicy?.(U,te),ue.success(`Policy "${U.metadata.name}" saved.`),x(null),h(""),await L()}catch{ue.error("Failed to save policy.")}finally{S(!1)}},de=async U=>{window.confirm(`Delete policy "${U}"?`)&&(await Ee.deletePolicy?.(U,te),ue.success("Policy deleted."),await L())},q=async U=>{i(re=>re.map(De=>De.metadata.id===U.metadata.id?{...De,metadata:{...De.metadata,enabled:!De.metadata.enabled}}:De));try{await Ee.patchPolicy?.(U.metadata.id,{enabled:!U.metadata.enabled},te)}catch{ue.error("Failed to toggle policy."),await L()}},pe=U=>{Ne(U.metadata.id),se({name:U.metadata.name,description:U.metadata.description,tags:(U.metadata.tags??[]).join(", "),priority:U.metadata.priority})},oe=()=>{Ne(null),se(null)},ze=async U=>{if(ye)try{await Ee.patchPolicy?.(U,{name:ye.name,description:ye.description,tags:ye.tags.split(",").map(re=>re.trim()).filter(Boolean),priority:ye.priority},te),ue.success("Policy updated."),Ne(null),se(null),await L()}catch{ue.error("Failed to save edits.")}},Be=U=>{h(U.metadata.description),A("policies"),ue.success("Description pre-filled — edit and click ✨ to re-synthesize.")},kt=async()=>{await Ee.reloadPolicies?.(te),await L(),ue.success("Policies reloaded.")},et=(U,re,De)=>{ge(qe=>{const ft=qe.actions.map((Zt,Ve)=>Ve===U?{...Zt,[re]:De}:Zt);return{...qe,actions:ft}})},ce=()=>{ge(U=>({...U,actions:[...U.actions,{type:"copy",destination:"",filename:"",columns:[],spreadsheet_id:"",range:""}]}))},Fe=U=>{ge(re=>({...re,actions:re.actions.filter((De,qe)=>qe!==U)}))},he=U=>U.type==="append_to_google_sheet"&&!U.spreadsheet_id?.trim(),Me=J.actions.some(he),at=async()=>{if(!J.name.trim())return;const U=J.actions.findIndex(he);if(U!==-1){ue.error(`Action #${U+1}: "Append to Google Sheet" requires Spreadsheet ID or Google Sheet URL.`);return}D(!0);try{const re=J.name.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),De=J.keywords.split(",").map(Ve=>Ve.trim()).filter(Boolean),qe=J.tags.split(",").map(Ve=>Ve.trim()).filter(Boolean),ft=J.actions.filter(Ve=>Ve.type==="copy_to_gdrive"||Ve.type==="auto_rename"||Ve.type==="append_to_google_sheet"||Ve.destination.trim()).map(Ve=>{const en={type:Ve.type};if(Ve.type==="copy")en.destination=Ve.destination,Ve.filename&&(en.filename=Ve.filename);else if(Ve.type==="rename")en.destination=Ve.destination;else if(Ve.type!=="auto_rename"){if(Ve.type==="copy_to_gdrive")Ve.destination.trim()&&(en.destination=Ve.destination.trim()),Ve.filename&&(en.filename=Ve.filename);else if(Ve.type==="log_csv")en.path=Ve.destination;else if(Ve.type==="append_to_google_sheet"){const ll=Ve.spreadsheet_id?.trim();ll&&(en.spreadsheet_id=ll);const Ms=Ve.range?.trim();Ms&&(en.range=Ms);const Kt=(Ve.columns??[]).map(Wn=>Wn.trim()).filter(Boolean);Kt.length>0&&(en.columns=Kt)}}return en}),Zt={metadata:{id:re,name:J.name.trim(),description:J.description.trim(),priority:J.priority,tags:qe,enabled:!0},spec:{match:{strategy:J.matchStrategy,conditions:De.length>0?[{type:"keyword",value:De}]:[{type:"keyword",value:[]}]},extract:[],actions:ft}};await Ee.savePolicy?.(Zt,te),ue.success(`Policy "${Zt.metadata.name}" created.`),F(!1),ge({name:"",description:"",keywords:"",matchStrategy:"ANY",actions:[{type:"copy",destination:"",filename:"",columns:[],spreadsheet_id:"",range:""}],tags:"",priority:100}),await L()}catch{ue.error("Failed to create policy.")}finally{D(!1)}},Ut=U=>{if(U.type==="append_to_google_sheet"){const re=U.spreadsheet_id?.trim()||U.spreadsheet_url?.trim()||"",De=U.range?.trim()||"";return re&&De?`${re} (${De})`:re||De}return U.type==="log_csv"?U.path?.trim()||"":U.destination?.trim()||U.pattern?.trim()||""},Xn=(U,re)=>{x(De=>{if(!De)return De;const qe=(De.spec.actions??[]).map((ft,Zt)=>Zt===U?{...ft,...re}:ft);return{...De,spec:{...De.spec,actions:qe}}})},jr=(U=>{if(!U)return[];const re=[];U.metadata.name?.trim()||re.push("Policy name is missing."),U.metadata.id?.trim()||re.push("Policy id is missing.");const De=U.spec.actions??[];return De.length===0&&re.push("At least one action is required."),De.forEach((qe,ft)=>{qe.type==="append_to_google_sheet"&&(qe.spreadsheet_id?.trim()||qe.spreadsheet_url?.trim()||re.push(`Action #${ft+1} append_to_google_sheet is missing spreadsheet_id / URL.`)),qe.type==="copy"&&!qe.destination?.trim()&&re.push(`Action #${ft+1} copy is missing destination.`),qe.type==="rename"&&!(qe.pattern?.trim()||qe.destination?.trim())&&re.push(`Action #${ft+1} rename is missing pattern.`)}),re})(y),Uu=!!y&&jr.length===0&&!T;return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-10 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex items-end justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"text-3xl font-black tracking-tight flex items-center gap-3",children:[o.jsx(Hw,{className:"w-8 h-8 text-primary"}),"Policy Engine"]}),o.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Define automation rules that govern how Folio handles your documents."})]}),o.jsxs(ae,{variant:"outline",size:"sm",onClick:kt,className:"gap-2 rounded-xl",children:[o.jsx(ma,{className:"w-4 h-4"}),"Reload"]})]}),o.jsx("div",{className:"flex gap-1 p-1 rounded-2xl bg-muted/50 border w-fit",children:["policies","packs"].map(U=>o.jsx("button",{onClick:()=>A(U),className:ve("px-5 py-2 rounded-xl text-xs font-black uppercase tracking-widest transition-all",C===U?"bg-background shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"),children:U==="policies"?"Active Policies":"Policy Packs"},U))}),C==="policies"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-2xl border bg-card/60 backdrop-blur-sm p-6 shadow-sm space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx(Cs,{className:"w-4 h-4 text-primary"}),o.jsx("h2",{className:"text-sm font-black uppercase tracking-widest",children:"Magic Composer"})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Describe a rule in plain English. Click ✨ to generate the policy automatically."}),k.length>0&&o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsx(Bm,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),o.jsx("select",{value:`${P}::${R}`,onChange:U=>{const[re,De]=U.target.value.split("::");B(re),I(De)},className:"text-xs rounded-lg border border-border/40 bg-background px-2 py-1 text-foreground flex-1 max-w-xs",children:k.flatMap(U=>(U.models??[]).map(re=>o.jsxs("option",{value:`${U.provider}::${re.id}`,children:[U.provider," / ",re.id]},`${U.provider}::${re.id}`)))}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:"for synthesis"})]}),o.jsxs("div",{className:"flex gap-3 items-start",children:[o.jsx(Ym,{placeholder:"e.g. If I get a bill from Tesla, move it to /Car/ folder and log the amount to my CSV…",value:d,onChange:U=>h(U.target.value),className:"flex-1 min-h-[80px] resize-none rounded-xl border-border/40 bg-background text-sm",onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&ee()}}),o.jsx(ae,{onClick:ee,disabled:m||!d.trim(),className:ve("h-10 w-10 p-0 rounded-xl flex items-center justify-center transition-all","bg-primary text-primary-foreground shadow-lg shadow-primary/20","hover:scale-105 active:scale-95"),title:"Synthesize policy with AI",children:m?o.jsx(rt,{className:"w-4 h-4 animate-spin"}):o.jsx(Cs,{className:"w-4 h-4"})})]}),y&&o.jsxs("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-4 space-y-3 animate-in slide-in-from-bottom-2 duration-300",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("p",{className:"font-black text-sm",children:y.metadata.name}),o.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:y.metadata.description})]}),o.jsxs(Mt,{variant:"outline",className:"text-[10px] uppercase font-bold",children:["Priority ",y.metadata.priority]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 text-xs text-muted-foreground",children:[o.jsxs("div",{className:"rounded-lg bg-muted/60 p-2",children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] mb-1 text-foreground",children:"Match"}),o.jsxs("div",{className:"space-y-1",children:[y.spec.match.conditions.length===0&&o.jsx("div",{children:"—"}),y.spec.match.conditions.map((U,re)=>o.jsxs("div",{children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:U.type})," ",Array.isArray(U.value)?U.value.join(", "):U.value]},`${U.type}-${re}`))]})]}),o.jsxs("div",{className:"rounded-lg bg-muted/60 p-2",children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] mb-1 text-foreground",children:"Extract"}),o.jsxs("div",{className:"space-y-1",children:[(y.spec.extract?.length??0)===0&&o.jsx("div",{children:"—"}),y.spec.extract?.map(U=>o.jsxs("div",{children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:U.key})," ","(",U.type,")",U.required?" *":""]},U.key))]})]}),o.jsxs("div",{className:"rounded-lg bg-muted/60 p-2",children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] mb-1 text-foreground",children:"Actions"}),o.jsxs("div",{className:"space-y-2",children:[(y.spec.actions?.length??0)===0&&o.jsx("div",{children:"—"}),y.spec.actions?.map((U,re)=>o.jsxs("div",{className:"rounded-md border border-border/50 bg-background/80 p-2 space-y-1.5",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:U.type})," ",Ut(U)]}),U.type==="copy_to_gdrive"&&o.jsx(_e,{value:U.destination??"",onChange:De=>Xn(re,{destination:De.target.value}),placeholder:"Google Drive folder ID",className:"h-7 text-[11px] rounded-lg font-mono"}),U.type==="append_to_google_sheet"&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(_e,{value:U.spreadsheet_id??U.spreadsheet_url??"",onChange:De=>Xn(re,{spreadsheet_id:De.target.value,spreadsheet_url:void 0}),placeholder:"Spreadsheet ID or URL",className:"h-7 text-[11px] rounded-lg font-mono"}),o.jsx(_e,{value:U.range??"",onChange:De=>Xn(re,{range:De.target.value}),placeholder:"Optional range (e.g. Sheet1!A:Z)",className:"h-7 text-[11px] rounded-lg font-mono"})]})]},`${U.type}-${re}`))]})]})]}),jr.length>0?o.jsx(jn,{className:"rounded-xl border-red-200 bg-red-50",children:o.jsxs(_n,{className:"text-xs text-red-700",children:[o.jsx("div",{className:"font-semibold mb-1",children:"Fix before saving:"}),o.jsx("div",{className:"space-y-0.5",children:jr.map((U,re)=>o.jsx("div",{children:U},`synth-issue-${re}`))})]})}):o.jsx("div",{className:"text-[11px] text-emerald-700 font-semibold",children:"Policy looks valid for save."}),o.jsx("div",{className:"flex gap-2",children:o.jsx(ae,{type:"button",size:"sm",variant:"outline",onClick:()=>j(U=>!U),className:"h-7 px-2 rounded-lg text-[10px] uppercase tracking-widest",children:w?"Hide JSON":"Show JSON"})}),w&&o.jsx("pre",{className:"rounded-lg border border-border/40 bg-background p-3 text-[11px] overflow-auto max-h-72 whitespace-pre-wrap font-mono",children:JSON.stringify(y,null,2)}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx(ae,{size:"sm",onClick:()=>le(y),disabled:!Uu,className:"flex-1 h-8 rounded-xl font-black text-[10px] uppercase tracking-widest",children:T?o.jsx(rt,{className:"w-3 h-3 animate-spin"}):"Save Policy"}),o.jsx(ae,{size:"sm",variant:"outline",onClick:()=>{x(null),j(!1)},className:"h-8 px-3 rounded-xl",children:"Discard"})]})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("h2",{className:"text-xs font-black uppercase tracking-widest text-muted-foreground",children:["Active Policies (",s.length,")"]}),o.jsx(ae,{size:"sm",variant:V?"secondary":"outline",onClick:()=>F(U=>!U),className:"h-7 px-3 rounded-xl gap-1.5 text-[10px] font-black uppercase tracking-widest",children:V?o.jsxs(o.Fragment,{children:[o.jsx(zn,{className:"w-3 h-3"}),"Cancel"]}):o.jsxs(o.Fragment,{children:[o.jsx(hu,{className:"w-3 h-3"}),"Quick Create"]})})]}),V&&o.jsxs("div",{className:"rounded-2xl border border-primary/20 bg-primary/5 p-5 space-y-4 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(hu,{className:"w-3.5 h-3.5 text-primary"}),o.jsx("span",{className:"text-xs font-black uppercase tracking-widest text-primary",children:"Quick Create Policy"})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"col-span-2 space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Name *"}),o.jsx(_e,{placeholder:"e.g. Tesla Invoice Handler",value:J.name,onChange:U=>ge({...J,name:U.target.value}),className:"h-8 text-sm rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"col-span-2 space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Description"}),o.jsx(_e,{placeholder:"What does this policy do?",value:J.description,onChange:U=>ge({...J,description:U.target.value}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Match Keywords"}),o.jsx(_e,{placeholder:"tesla, invoice, PG&E (comma-sep)",value:J.keywords,onChange:U=>ge({...J,keywords:U.target.value}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Match Strategy"}),o.jsxs("select",{value:J.matchStrategy,onChange:U=>ge({...J,matchStrategy:U.target.value}),className:"h-8 w-full text-xs rounded-xl border border-border/40 bg-background px-3 text-foreground",children:[o.jsx("option",{value:"ANY",children:"ANY keyword matches"}),o.jsx("option",{value:"ALL",children:"ALL keywords match"})]})]}),o.jsxs("div",{className:"col-span-2 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Actions"}),o.jsxs("button",{type:"button",onClick:ce,className:"flex items-center gap-1 text-[10px] font-bold text-primary hover:text-primary/80 transition-colors",children:[o.jsx(Ja,{className:"w-3 h-3"}),"Add Action"]})]}),o.jsx("div",{className:"space-y-2",children:J.actions.map((U,re)=>{const De=!U.filename||U.filename===""?"original":U.filename==="auto"?"auto":"custom";return o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-2 items-start",children:[o.jsxs("select",{value:U.type,onChange:qe=>et(re,"type",qe.target.value),className:"h-8 text-xs rounded-xl border border-border/40 bg-background px-2 text-foreground w-full",children:[o.jsx("option",{value:"copy",children:"Copy to folder"}),o.jsx("option",{value:"rename",children:"Rename file (Pattern)"}),o.jsx("option",{value:"log_csv",children:"Log to CSV"}),o.jsx("option",{value:"copy_to_gdrive",children:"Copy to Google Drive"}),o.jsx("option",{value:"append_to_google_sheet",children:"Append to Google Sheet"})]}),o.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[U.type!=="append_to_google_sheet"&&o.jsx(_e,{placeholder:U.type==="copy"?"/Car/":U.type==="copy_to_gdrive"?"Folder ID (empty = My Drive root)":U.type==="rename"?"Tesla-{date}":"/logs/invoices.csv",value:U.destination,onChange:qe=>et(re,"destination",qe.target.value),className:"h-8 text-xs rounded-xl border-border/40 bg-background font-mono flex-1 min-w-0"}),J.actions.length>1&&o.jsx("button",{type:"button",onClick:()=>Fe(re),className:"text-muted-foreground hover:text-destructive transition-colors shrink-0 p-1",children:o.jsx(zn,{className:"w-3.5 h-3.5"})})]})]}),(U.type==="copy"||U.type==="copy_to_gdrive")&&o.jsxs("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-2 items-center",children:[o.jsx("div",{"aria-hidden":"true"}),o.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[o.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:"Filename:"}),o.jsxs("select",{value:De,onChange:qe=>{const ft=qe.target.value;ft==="original"?et(re,"filename",""):ft==="auto"?et(re,"filename","auto"):et(re,"filename","{date}_{issuer}_{document_type}")},className:"h-7 text-xs rounded-lg border border-border/40 bg-background px-2 text-foreground shrink-0",children:[o.jsx("option",{value:"original",children:"Keep original"}),o.jsx("option",{value:"auto",children:"Smart rename (AI)"}),o.jsx("option",{value:"custom",children:"Custom pattern"})]}),De==="custom"&&o.jsx(_e,{value:U.filename,onChange:qe=>et(re,"filename",qe.target.value),placeholder:"{date}_{issuer}_{document_type}",className:"h-7 text-xs rounded-lg border-border/40 bg-background font-mono flex-1 min-w-0"})]})]}),U.type==="append_to_google_sheet"&&o.jsxs("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-2",children:[o.jsx("div",{"aria-hidden":"true"}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx(_e,{placeholder:"Spreadsheet ID or Google Sheet URL",value:U.spreadsheet_id||"",onChange:qe=>et(re,"spreadsheet_id",qe.target.value),className:"h-7 text-xs rounded-lg flex-1"}),o.jsx(_e,{placeholder:"Optional tab/range (e.g. Sheet1!A:F)",value:U.range||"",onChange:qe=>et(re,"range",qe.target.value),className:"h-7 text-xs rounded-lg w-32"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 p-2 rounded-lg border border-border/40 bg-muted/20",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Je,{className:"text-[10px] uppercase font-bold text-muted-foreground",children:"Columns Mapping (A, B, C...)"}),o.jsxs(ae,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-[10px] px-2 py-0",onClick:()=>{const qe=[...U.columns||[],""];et(re,"columns",qe)},children:[o.jsx(Ja,{className:"w-3 h-3 mr-1"})," Add Col"]})]}),(U.columns||[]).map((qe,ft)=>o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-[10px] font-mono text-muted-foreground w-4 flex-shrink-0 text-center",children:String.fromCharCode(65+ft)}),o.jsx(_e,{placeholder:"e.g. {Date} or Static Text",value:qe,onChange:Zt=>{const Ve=[...U.columns||[]];Ve[ft]=Zt.target.value,et(re,"columns",Ve)},className:"h-7 text-xs rounded-lg font-mono flex-1"}),o.jsx("button",{type:"button",onClick:()=>{const Zt=(U.columns||[]).filter((Ve,en)=>en!==ft);et(re,"columns",Zt)},className:"text-muted-foreground hover:text-destructive p-1",children:o.jsx(zn,{className:"w-3 h-3"})})]},ft)),(!U.columns||U.columns.length===0)&&o.jsx("div",{className:"text-[10px] text-muted-foreground italic text-center py-1",children:"No explicit mapping provided. Folio will auto-map by reading header row from the sheet template."})]})]})]})]},re)})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Tags"}),o.jsx(_e,{placeholder:"finance, cars (comma-sep)",value:J.tags,onChange:U=>ge({...J,tags:U.target.value}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Priority"}),o.jsx(_e,{type:"number",min:1,max:999,value:J.priority,onChange:U=>ge({...J,priority:Number(U.target.value)}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]})]}),Me&&o.jsx("p",{className:"text-[10px] text-destructive",children:'"Append to Google Sheet" actions require a Spreadsheet ID or Google Sheet URL.'}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx(ae,{size:"sm",onClick:at,disabled:ne||!J.name.trim()||Me,className:"flex-1 h-8 rounded-xl font-black text-[10px] uppercase tracking-widest gap-1.5",children:ne?o.jsx(rt,{className:"w-3 h-3 animate-spin"}):o.jsxs(o.Fragment,{children:[o.jsx(Ja,{className:"w-3 h-3"}),"Create Policy"]})}),o.jsx(ae,{size:"sm",variant:"outline",onClick:()=>F(!1),className:"h-8 px-3 rounded-xl",children:"Cancel"})]})]}),l?o.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[o.jsx(rt,{className:"w-6 h-6 animate-spin mr-3"}),"Loading policies..."]}):s.length===0?o.jsxs(jn,{className:"rounded-2xl border-dashed",children:[o.jsx(Im,{className:"h-4 w-4"}),o.jsx(_n,{className:"text-sm",children:"No policies yet. Use the Magic Composer above to create your first one."})]}):o.jsx("div",{className:"space-y-2",children:s.map(U=>o.jsxs("div",{className:ve("rounded-2xl border bg-card/50 shadow-sm overflow-hidden transition-all",U.metadata.enabled===!1&&"opacity-60"),children:[o.jsxs("div",{className:"flex items-center gap-3 px-5 py-4",children:[o.jsx("button",{title:U.metadata.enabled===!1?"Enable policy":"Disable policy",onClick:()=>q(U),className:"shrink-0 text-muted-foreground hover:text-foreground transition-colors",children:U.metadata.enabled===!1?o.jsx(lA,{className:"w-5 h-5 text-muted-foreground"}):o.jsx(uA,{className:"w-5 h-5 text-primary"})}),o.jsx("div",{className:"flex-1 min-w-0",children:fe===U.metadata.id&&ye?o.jsxs("div",{className:"space-y-2",onClick:re=>re.stopPropagation(),children:[o.jsx(_e,{value:ye.name,onChange:re=>se({...ye,name:re.target.value}),placeholder:"Policy name",className:"h-7 text-sm font-semibold"}),o.jsx(_e,{value:ye.description,onChange:re=>se({...ye,description:re.target.value}),placeholder:"Description",className:"h-7 text-xs"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(_e,{value:ye.tags,onChange:re=>se({...ye,tags:re.target.value}),placeholder:"Tags (comma-separated)",className:"h-7 text-xs flex-1"}),o.jsx(_e,{type:"number",value:ye.priority,onChange:re=>se({...ye,priority:Number(re.target.value)}),placeholder:"Priority",className:"h-7 text-xs w-20",min:1,max:999})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"font-bold text-sm truncate",children:U.metadata.name}),o.jsxs(Mt,{variant:"outline",className:"text-[9px] shrink-0",children:["P",U.metadata.priority]}),(U.metadata.learning_examples??0)>0&&o.jsxs(Mt,{variant:"secondary",className:"text-[9px] shrink-0",children:["Learned ",U.metadata.learning_examples]}),U.metadata.tags?.map(re=>o.jsxs(Mt,{variant:"secondary",className:"text-[9px] gap-1 shrink-0",children:[o.jsx(du,{className:"w-2.5 h-2.5"}),re]},re))]}),o.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:U.metadata.description})]})}),o.jsx("div",{className:"flex items-center gap-1 shrink-0",children:fe===U.metadata.id?o.jsxs(o.Fragment,{children:[o.jsx(ae,{size:"sm",variant:"default",className:"h-7 px-2 text-xs",onClick:()=>ze(U.metadata.id),children:"Save"}),o.jsx(ae,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:oe,children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{title:"Edit metadata",onClick:()=>pe(U),className:"text-muted-foreground hover:text-foreground transition-colors p-1",children:o.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-4 h-4",children:[o.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),o.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),o.jsx("button",{title:"Re-compose with AI",onClick:()=>Be(U),className:"text-muted-foreground hover:text-primary transition-colors p-1",children:o.jsx(Cs,{className:"w-4 h-4"})}),o.jsx("button",{className:"text-muted-foreground hover:text-foreground transition-colors p-1",onClick:()=>E(_===U.metadata.id?null:U.metadata.id),children:_===U.metadata.id?o.jsx(lu,{className:"w-4 h-4"}):o.jsx(Bo,{className:"w-4 h-4"})}),o.jsx("button",{onClick:()=>de(U.metadata.id),className:"text-muted-foreground hover:text-destructive transition-colors p-1",children:o.jsx(el,{className:"w-4 h-4"})})]})})]}),_===U.metadata.id&&o.jsxs("div",{className:"border-t px-5 py-4 bg-muted/20 space-y-3 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3 text-xs",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"font-bold uppercase tracking-widest text-[9px] text-muted-foreground mb-1",children:["Match (",U.spec.match.strategy,")"]}),U.spec.match.conditions.map((re,De)=>o.jsxs("div",{className:"text-muted-foreground",children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:re.type})," ",Array.isArray(re.value)?re.value.join(", "):re.value]},De))]}),o.jsxs("div",{children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] text-muted-foreground mb-1",children:"Extract"}),U.spec.extract?.map(re=>o.jsxs("div",{className:"text-muted-foreground",children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:re.key})," ","(",re.type,")",re.required?" *":""]},re.key))??o.jsx("span",{className:"text-muted-foreground/60",children:"—"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] text-muted-foreground mb-1",children:"Actions"}),U.spec.actions?.map((re,De)=>o.jsxs("div",{className:"text-muted-foreground",children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:re.type})," ",Ut(re)]},De))??o.jsx("span",{className:"text-muted-foreground/60",children:"—"})]})]}),(U.metadata.learning_examples??0)>0&&o.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Learned examples: ",U.metadata.learning_examples,U.metadata.learning_last_at?` · last on ${new Date(U.metadata.learning_last_at).toLocaleDateString()}`:""]})]})]},U.metadata.id))})]})]}),C==="packs"&&o.jsxs("div",{className:"space-y-4",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"Import curated policy bundles to instantly configure Folio for common use cases."}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:R6.map(U=>o.jsxs("div",{className:"rounded-2xl border bg-card/60 p-5 space-y-3 hover:border-primary/30 hover:shadow-md transition-all group",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"font-black text-sm",children:U.name}),o.jsxs(Mt,{variant:"outline",className:"text-[9px] shrink-0",children:[U.policies," policies"]})]}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:U.description})]}),o.jsx("div",{className:"flex flex-wrap gap-1",children:U.tags.map(re=>o.jsxs(Mt,{variant:"secondary",className:"text-[9px] gap-1",children:[o.jsx(du,{className:"w-2.5 h-2.5"}),re]},re))}),o.jsxs(ae,{size:"sm",variant:"outline",className:"w-full h-8 rounded-xl font-black text-[10px] uppercase tracking-widest group-hover:border-primary/40 transition-all",onClick:()=>ue.info(`"${U.name}" import coming soon!`),children:[o.jsx(RC,{className:"w-3 h-3 mr-2"}),"Import Pack"]})]},U.id))})]})]})}function Wa(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Wb(t){const e=[];for(const s of t){const i=Wa(s);if(!i)continue;const l=Wa(i.metadata)??{},u=Wa(i.spec)??{},d=Array.isArray(u.actions)?u.actions:[],h=typeof l.id=="string"?l.id.trim():"";if(!h)continue;const m=d.map(p=>{const y=Wa(p);return typeof y?.type=="string"?y.type.trim():""}).filter(p=>p==="append_to_google_sheet"||p==="webhook"||p==="copy_to_gdrive"||p==="copy"||p==="log_csv"||p==="notify");e.push({id:h,name:typeof l.name=="string"?l.name:h,priority:typeof l.priority=="number"?l.priority:100,riskyActions:m,learningExamples:typeof l.learning_examples=="number"?l.learning_examples:0,learningLastAt:typeof l.learning_last_at=="string"?l.learning_last_at:null})}return e.sort((s,i)=>i.priority-s.priority),e}function M6(t){if(!Array.isArray(t)||t.length===0)return null;const s=[...t].reverse().find(h=>{const m=String(h?.step??"").toLowerCase();return m.includes("learned fallback")||m.includes("learned policy candidate selected")});if(!s)return null;const i=String(s.step??"").toLowerCase(),l=Wa(s.details);if(!l)return null;const u=typeof l.reason=="string"?l.reason:i.includes("candidate selected")?"accepted":void 0,d=Wa(l.bestCandidate)??(typeof l.policyId=="string"||typeof l.score=="number"||typeof l.support=="number"?{policyId:l.policyId,score:l.score,support:l.support}:void 0);return{reason:u,evaluatedPolicies:typeof l.evaluatedPolicies=="number"?l.evaluatedPolicies:void 0,evaluatedSamples:typeof l.evaluatedSamples=="number"?l.evaluatedSamples:void 0,bestCandidate:d,topCandidates:Array.isArray(l.topCandidates)?l.topCandidates.map(h=>Wa(h)).filter(h=>!!h):void 0}}function D6(t){if(!t)return"No learned candidate details available yet.";switch(t){case"accepted":return"Learned fallback selected a policy candidate.";case"no_policy_ids":return"No candidate policies available for learned fallback.";case"no_document_features":return"Document had insufficient signals for learned fallback scoring.";case"no_feedback_samples":return"No learned examples yet. Match at least one document with learning enabled.";case"no_valid_samples":return"Learned examples exist but were too sparse to score.";case"score_below_threshold":return"A candidate was found but confidence stayed below threshold.";case"read_error":return"Learned fallback could not read feedback history.";default:return t.replace(/_/g," ")}}function P6({status:t}){return{pending:o.jsx(Qo,{className:"w-4 h-4 text-muted-foreground"}),processing:o.jsx(rt,{className:"w-4 h-4 text-blue-500 animate-spin"}),matched:o.jsx(os,{className:"w-4 h-4 text-emerald-500"}),no_match:o.jsx(em,{className:"w-4 h-4 text-amber-500"}),duplicate:o.jsx(em,{className:"w-4 h-4 text-emerald-500"}),error:o.jsx(Lw,{className:"w-4 h-4 text-destructive"})}[t]??null}function ra({children:t}){return o.jsx("div",{className:"text-[9px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5",children:t})}function z6(t){const e=[];t.status==="no_match"?e.push(`I have a document named "${t.filename}" that wasn't matched by any policy.`):e.push(`I have a document named "${t.filename}" that matched a policy, but I want to create a better, more specific policy for it.`),t.mime_type&&e.push(`It is a ${t.mime_type} file.`);const s=t.extracted?Object.entries(t.extracted).filter(([i,l])=>i!=="_enrichment"&&l!=null):[];if(s.length>0){const i=s.map(([l,u])=>`${l}: ${String(u)}`).join(", ");e.push(`Partial data already extracted: ${i}.`)}return e.push("Create a policy to handle this exact type of document — infer the document type, define strict match conditions, extract key fields, and route it to an appropriate folder."),e.join(" ")}function Jb(t){if(t==null)return"null";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t)}catch{return String(t)}}const L6=["issuer","vendor","sender","document_type","date","due_date","amount","total","currency"];function U6({extracted:t}){const e=L6.filter(s=>t[s]!=null&&String(t[s]).trim()!=="").map(s=>({key:s,value:String(t[s])}));return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.map(({key:s,value:i})=>o.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-muted border",children:[o.jsx("span",{className:"text-muted-foreground font-mono",children:s}),o.jsx("span",{className:"font-medium",children:i})]},s))})}function B6({tags:t,onChange:e}){const[s,i]=v.useState(""),l=v.useRef(null),u=m=>e(t.filter(p=>p!==m)),d=()=>{const m=s.toLowerCase().trim().replace(/\s+/g,"-");if(!m||t.includes(m)){i("");return}e([...t,m]),i("")},h=m=>{m.key==="Enter"||m.key===","?(m.preventDefault(),d()):m.key==="Backspace"&&!s&&t.length>0&&e(t.slice(0,-1))};return o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 rounded-xl border px-3 py-2 bg-background min-h-[36px] cursor-text",role:"button",tabIndex:0,onClick:()=>l.current?.focus(),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),l.current?.focus())},children:[t.map(m=>o.jsxs("span",{className:ve("inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full border",kp(m)),children:[m,o.jsx("button",{onClick:p=>{p.stopPropagation(),u(m)},className:"ml-0.5 opacity-60 hover:opacity-100 transition-opacity","aria-label":`Remove ${m}`,children:o.jsx(zn,{className:"w-2.5 h-2.5"})})]},m)),o.jsx("input",{ref:l,value:s,onChange:m=>i(m.target.value),onKeyDown:h,onBlur:d,placeholder:t.length?"":"Add tags…",className:"flex-1 min-w-[80px] bg-transparent text-xs outline-none placeholder:text-muted-foreground/50"}),s&&o.jsx("button",{onClick:d,className:"text-muted-foreground hover:text-foreground transition-colors",children:o.jsx(Ja,{className:"w-3 h-3"})})]})}function V6({ingestion:t,onClose:e,onRerun:s,onTagsChange:i,onComposePolicy:l,onManualMatch:u}){const d=t.extracted&&Object.keys(t.extracted).length>0?t.extracted:null,h=d&&typeof d._enrichment=="object"&&d._enrichment!==null?d._enrichment:null,m=t.actions_taken?.length?t.actions_taken:null,[p,y]=v.useState(t.summary??null),[x,w]=v.useState(!1),[j,T]=v.useState([]),[S,_]=v.useState(!1),[E,C]=v.useState(""),[A,k]=v.useState(!0),[M,P]=v.useState(!0),[B,R]=v.useState(!1),[I,te]=v.useState(!1),[ie,fe]=v.useState(null),[Ne,ye]=v.useState(!1),[se,V]=v.useState(!1),[F,J]=v.useState(null),[ge,ne]=v.useState([]),[D,L]=v.useState(null),[W,ee]=v.useState(!1),le=t.status!=="pending"&&t.status!=="processing",de=!!u&&!t.policy_name&&t.status!=="pending"&&t.status!=="processing",q=M6(t.trace);v.useEffect(()=>{if(!le||p)return;let ce=!1;return(async()=>{w(!0);try{const he=(await un()?.auth.getSession())?.data?.session?.access_token??null,Me=await Ee.summarizeIngestion(t.id,he);if(ce)return;Me.data?.summary&&y(Me.data.summary)}catch{}finally{ce||w(!1)}})(),()=>{ce=!0}},[t.id]),v.useEffect(()=>{if(!de)return;let ce=!1;return(async()=>{_(!0),fe(null);try{const he=(await un()?.auth.getSession())?.data?.session?.access_token??null,Me=await Ee.getPolicies(he);if(ce)return;if(Me?.error){const Ut=typeof Me.error=="string"?Me.error:Me.error.message;throw new Error(Ut||"Failed to load policies.")}const at=Wb(Me?.data?.policies??[]);T(at),C(Ut=>Ut||at[0]?.id||"")}catch{ce||(T([]),fe("Failed to load policies."))}finally{ce||_(!1)}})(),()=>{ce=!0}},[de,t.id]);const pe=v.useCallback(async()=>{if(!u||!E||I)return;const Fe=j.find(he=>he.id===E)?.riskyActions??[];if(M&&Fe.length>0&&!B){fe(`Re-run may trigger side-effect actions: ${Fe.join(", ")}. Enable side-effect confirmation to continue.`);return}te(!0),fe(null);try{await u({policyId:E,learn:A,rerun:M,allowSideEffects:M?B:!1}),J(null),ne([]),L(null)}catch(he){const Me=he instanceof Error?he.message:String(he);fe(Me||"Failed to assign policy.")}finally{te(!1)}},[B,I,A,u,j,M,E]),oe=v.useCallback(async()=>{if(!(!E||Ne||se)){ye(!0),L(null),J(null),ne([]);try{const Fe=(await un()?.auth.getSession())?.data?.session?.access_token??null,he=await Ee.suggestPolicyRefinement(t.id,{policyId:E},Fe);if(he?.error){const Ut=typeof he.error=="string"?he.error:he.error.message;throw new Error(Ut||"Unable to suggest refinement.")}const Me=he?.data?.suggestion?.policy;if(!Me)throw new Error("No policy refinement draft was returned.");const at=Array.isArray(he?.data?.suggestion?.rationale)?he.data.suggestion.rationale.map(Ut=>String(Ut).trim()).filter(Boolean):[];J(Me),ne(at),ee(!1)}catch(ce){const Fe=ce instanceof Error?ce.message:String(ce);L(Fe||"Unable to suggest refinement.")}finally{ye(!1)}}},[t.id,se,Ne,E]),ze=v.useCallback(async()=>{if(!(!F||se)){V(!0),L(null);try{const Fe=(await un()?.auth.getSession())?.data?.session?.access_token??null,he=await Ee.savePolicy(F,Fe);if(he?.error){const at=typeof he.error=="string"?he.error:he.error.message;throw new Error(at||"Failed to apply refinement.")}ue.success(`Applied refinement to policy "${F.metadata.name}".`),J(null),ne([]),L(null),ee(!1);const Me=await Ee.getPolicies(Fe);if(!Me?.error){const at=Wb(Me?.data?.policies??[]);T(at)}}catch(ce){const Fe=ce instanceof Error?ce.message:String(ce);L(Fe||"Failed to apply refinement.")}finally{V(!1)}}},[se,F]),Be=j.find(ce=>ce.id===E),kt=Be?.riskyActions??[],et=v.useCallback(ce=>{ce.target===ce.currentTarget&&e()},[e]);return o.jsx("div",{className:"fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4",role:"button",tabIndex:0,onClick:et,onKeyDown:ce=>{ce.key==="Escape"&&(ce.preventDefault(),e()),(ce.key==="Enter"||ce.key===" ")&&ce.target===ce.currentTarget&&(ce.preventDefault(),e())},children:o.jsxs("div",{className:"bg-background border rounded-2xl shadow-2xl w-full max-w-xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-200",children:[o.jsxs("div",{className:"flex items-start gap-3 px-6 pt-5 pb-4 border-b",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-muted flex items-center justify-center shrink-0 mt-0.5",children:o.jsx(Vm,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h2",{className:"font-bold text-sm truncate",title:t.filename,children:t.filename}),o.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[t.source," · ",new Date(t.created_at).toLocaleString(),t.file_size&&` · ${(t.file_size/1024).toFixed(1)}KB`]})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx(P6,{status:t.status}),o.jsx("button",{onClick:e,className:"text-muted-foreground hover:text-foreground transition-colors",children:o.jsx(zn,{className:"w-4 h-4"})})]})]}),o.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto max-h-[65vh]",children:[le&&o.jsxs("div",{children:[o.jsx(ra,{children:o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx(Cs,{className:"w-2.5 h-2.5"}),"Summary"]})}),d&&o.jsx("div",{className:"mb-2",children:o.jsx(U6,{extracted:d})}),x?o.jsxs("div",{className:"space-y-2",children:[o.jsx("div",{className:"h-3 rounded bg-muted animate-pulse w-full"}),o.jsx("div",{className:"h-3 rounded bg-muted animate-pulse w-5/6"}),o.jsx("div",{className:"h-3 rounded bg-muted animate-pulse w-4/6"})]}):p?o.jsx("p",{className:"text-xs text-foreground/80 leading-relaxed",children:p}):o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No summary available."})]}),!le&&o.jsx("div",{className:"rounded-xl bg-muted/40 border px-4 py-3 text-xs text-muted-foreground text-center",children:"Summary will be available after processing completes."}),o.jsxs("div",{children:[o.jsx(ra,{children:o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx(du,{className:"w-2.5 h-2.5"}),"Tags"]})}),o.jsx(B6,{tags:t.tags??[],onChange:i}),o.jsx("p",{className:"text-[10px] text-muted-foreground mt-1.5",children:"Enter to add · Backspace to remove · spaces become hyphens"})]}),o.jsxs("div",{children:[o.jsx(ra,{children:"Policy Matched"}),t.policy_name?o.jsx(Mt,{variant:"secondary",children:t.policy_name}):o.jsxs("div",{className:"space-y-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"No policy matched"}),de&&o.jsxs("div",{className:"rounded-xl border bg-muted/20 p-3 space-y-2",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-wider font-semibold text-muted-foreground",children:"Assign To Existing Policy"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("select",{className:"flex-1 h-8 rounded-lg border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-primary/30",value:E,onChange:ce=>{C(ce.target.value),R(!1),fe(null),J(null),ne([]),L(null)},disabled:S||I||j.length===0,children:j.length===0?o.jsx("option",{value:"",children:S?"Loading policies…":"No active policies"}):j.map(ce=>o.jsx("option",{value:ce.id,children:ce.learningExamples>0?`${ce.name} (${ce.learningExamples} learned)`:ce.name},ce.id))}),o.jsx(ae,{variant:"outline",size:"sm",className:"h-8 rounded-lg",disabled:I||S||!E,onClick:pe,children:I?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):"Match To Policy"}),o.jsx(ae,{variant:"outline",size:"sm",className:"h-8 rounded-lg",disabled:Ne||se||S||!E,onClick:oe,children:Ne?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):"Suggest Refinement"})]}),Be&&o.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Learned examples for this policy: ",Be.learningExamples,Be.learningLastAt?` · last on ${new Date(Be.learningLastAt).toLocaleDateString()}`:""]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[o.jsx("input",{type:"checkbox",className:"rounded border-muted-foreground/40",checked:A,onChange:ce=>k(ce.target.checked),disabled:I}),"Learn from this match"]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[o.jsx("input",{type:"checkbox",className:"rounded border-muted-foreground/40",checked:M,onChange:ce=>{P(ce.target.checked),R(!1),fe(null)},disabled:I}),"Re-run ingestion now (recommended)"]}),M&&kt.length>0&&o.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 p-2 text-[11px] text-amber-700 space-y-1",children:[o.jsxs("p",{children:["This policy has side-effect actions: ",kt.join(", ")]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 text-[11px]",children:[o.jsx("input",{type:"checkbox",className:"rounded border-amber-500/40",checked:B,onChange:ce=>R(ce.target.checked),disabled:I}),"I understand this may create external writes on re-run"]})]}),(F||D)&&o.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-2.5 space-y-2",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-wider font-semibold text-primary",children:"Policy Refinement Preview"}),D&&o.jsx("p",{className:"text-[11px] text-destructive",children:D}),F&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-[11px] text-foreground/90",children:[F.metadata.name," · ",F.spec.match.conditions.length," match conditions · ",(F.spec.extract??[]).length," extract fields"]}),ge.length>0&&o.jsx("div",{className:"space-y-1",children:ge.map((ce,Fe)=>o.jsx("p",{className:"text-[10px] text-muted-foreground",children:ce},`refine-rationale-${Fe}`))}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx(ae,{variant:"outline",size:"sm",className:"h-7 rounded-lg text-[10px]",onClick:()=>ee(ce=>!ce),children:W?"Hide JSON":"Show JSON"}),o.jsx(ae,{size:"sm",className:"h-7 rounded-lg text-[10px]",onClick:ze,disabled:se,children:se?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):"Apply To Policy"}),o.jsx(ae,{variant:"ghost",size:"sm",className:"h-7 rounded-lg text-[10px]",onClick:()=>{J(null),ne([]),L(null),ee(!1)},children:"Discard"})]}),W&&o.jsx("pre",{className:"rounded-md border border-border/40 bg-background p-2 text-[10px] overflow-auto max-h-48 whitespace-pre-wrap font-mono",children:JSON.stringify(F,null,2)})]})]}),ie&&o.jsx("p",{className:"text-[11px] text-destructive",children:ie})]})]})]}),q&&o.jsxs("div",{children:[o.jsx(ra,{children:"Learning Diagnostics"}),o.jsxs("div",{className:"rounded-xl border bg-muted/20 px-4 py-3 space-y-1.5",children:[o.jsx("p",{className:"text-xs text-foreground/90",children:D6(q.reason)}),(q.evaluatedPolicies!==void 0||q.evaluatedSamples!==void 0)&&o.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Evaluated policies: ",q.evaluatedPolicies??0," · samples: ",q.evaluatedSamples??0]}),q.bestCandidate&&o.jsxs("p",{className:"text-[11px] text-muted-foreground font-mono",children:["Best: ",String(q.bestCandidate.policyId??"-")," · score ",String(q.bestCandidate.score??"-")," · support ",String(q.bestCandidate.support??"-"),q.bestCandidate.requiredScore!==void 0?` · needed ${String(q.bestCandidate.requiredScore)}`:""]})]})]}),d&&o.jsxs("div",{children:[o.jsx(ra,{children:"Extracted Data"}),o.jsx("div",{className:"rounded-xl border overflow-hidden",children:Object.entries(d).filter(([ce])=>ce!=="_enrichment").map(([ce,Fe])=>o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 text-xs border-b last:border-0",children:[o.jsx("span",{className:"font-mono text-muted-foreground",children:ce}),o.jsx("span",{className:"font-medium text-right max-w-[55%] truncate",children:Jb(Fe)})]},ce))})]}),h&&Object.keys(h).length>0&&o.jsxs("div",{children:[o.jsx(ra,{children:"Enrichment Data"}),o.jsx("div",{className:"rounded-xl border overflow-hidden",children:Object.entries(h).map(([ce,Fe])=>o.jsxs("div",{className:"px-4 py-2 text-xs border-b last:border-0",children:[o.jsx("div",{className:"font-mono text-muted-foreground mb-1",children:ce}),o.jsx("pre",{className:"font-medium whitespace-pre-wrap break-all",children:Jb(Fe)})]},ce))})]}),m&&o.jsxs("div",{children:[o.jsx(ra,{children:"Actions Taken"}),o.jsx("ul",{className:"space-y-1",children:m.map((ce,Fe)=>o.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[o.jsx(os,{className:"w-3 h-3 text-emerald-500 shrink-0"}),o.jsx("span",{className:"text-muted-foreground",children:String(ce)})]},Fe))})]}),t.error_message&&o.jsxs("div",{children:[o.jsx(ra,{children:"Error"}),o.jsx("div",{className:"rounded-xl bg-destructive/5 border border-destructive/20 px-4 py-3",children:o.jsx("p",{className:"text-xs text-destructive font-mono break-all",children:t.error_message})})]}),!d&&!m&&!t.error_message&&le&&!x&&!p&&o.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No extracted data or actions recorded."})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t bg-muted/20",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ae,{variant:"outline",size:"sm",onClick:s,className:"gap-2 rounded-xl",children:[o.jsx(ma,{className:"w-3.5 h-3.5"}),"Re-run"]}),l&&o.jsxs(ae,{variant:"outline",size:"sm",onClick:()=>l(z6(t)),className:"gap-2 rounded-xl border-primary/30 text-primary hover:bg-primary/5 hover:text-primary",children:[o.jsx(Cs,{className:"w-3.5 h-3.5"}),"Create Policy"]})]}),o.jsx(ae,{variant:"ghost",size:"sm",onClick:e,className:"rounded-xl",children:"Close"})]})]})})}function I6({children:t}){return o.jsx("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3",children:t})}function $6({ingestion:t,onClose:e}){return o.jsx("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200",children:o.jsxs("div",{className:"bg-card w-full max-w-3xl rounded-2xl shadow-xl border overflow-hidden flex flex-col max-h-[90vh]",children:[o.jsxs("div",{className:"px-6 py-4 border-b flex items-center justify-between bg-muted/20",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:o.jsx(Io,{className:"w-4 h-4 text-emerald-500"})}),o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold",children:"AI Processing Trace"}),o.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[400px]",title:t.filename,children:t.filename})]})]}),o.jsx("button",{onClick:e,className:"p-2 -mr-2 text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors",children:o.jsx(zn,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"p-6 overflow-y-auto space-y-6",children:t.trace&&t.trace.length>0?o.jsxs("div",{children:[o.jsx(I6,{children:"Execution Log"}),o.jsx("div",{className:"rounded-xl bg-zinc-950 text-emerald-400 p-4 font-mono text-[11px] space-y-3 overflow-x-auto border border-zinc-800 shadow-inner max-h-[60vh] overflow-y-auto",children:[...t.trace].reverse().map((s,i)=>o.jsxs("div",{className:`flex gap-3 leading-relaxed ${s.step.startsWith("---")?"text-zinc-500 my-4 text-center justify-center":""}`,children:[!s.step.startsWith("---")&&o.jsx("span",{className:"opacity-40 shrink-0",children:new Date(s.timestamp).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}),o.jsxs("div",{className:s.step.startsWith("---")?"font-bold uppercase tracking-widest":"",children:[o.jsx("span",{className:"font-semibold text-zinc-100",children:s.step}),s.details&&Object.keys(s.details).length>0&&o.jsxs("pre",{className:"mt-1 flex text-emerald-500/80 whitespace-pre-wrap text-[10px]",children:[o.jsx("span",{className:"select-none opacity-30 mr-2",children:"↳"}),JSON.stringify(s.details,null,2)]})]})]},i))})]}):o.jsx("p",{className:"text-sm text-muted-foreground text-center py-12 border-2 border-dashed rounded-xl",children:"No trace logs available for this ingestion."})})]})})}const Qb=["bg-blue-500/10 text-blue-600 border-blue-500/20","bg-emerald-500/10 text-emerald-600 border-emerald-500/20","bg-amber-500/10 text-amber-700 border-amber-500/20","bg-violet-500/10 text-violet-600 border-violet-500/20","bg-rose-500/10 text-rose-600 border-rose-500/20","bg-cyan-500/10 text-cyan-600 border-cyan-500/20","bg-orange-500/10 text-orange-600 border-orange-500/20"];function kp(t){let e=0;for(const s of t)e=e*31+s.charCodeAt(0)>>>0;return Qb[e%Qb.length]}function q6({status:t}){const e={pending:{label:"Pending",icon:o.jsx(Qo,{className:"w-3 h-3"}),cls:"bg-muted text-muted-foreground"},processing:{label:"Processing",icon:o.jsx(rt,{className:"w-3 h-3 animate-spin"}),cls:"bg-blue-500/10 text-blue-500"},matched:{label:"Matched",icon:o.jsx(os,{className:"w-3 h-3"}),cls:"bg-emerald-500/10 text-emerald-500"},no_match:{label:"No Match",icon:o.jsx(em,{className:"w-3 h-3"}),cls:"bg-amber-500/10 text-amber-600"},error:{label:"Error",icon:o.jsx(Lw,{className:"w-3 h-3"}),cls:"bg-destructive/10 text-destructive"},duplicate:{label:"Duplicate",icon:o.jsx(Qk,{className:"w-3 h-3"}),cls:"bg-violet-500/10 text-violet-500"}},s=e[t]??e.pending;return o.jsxs("span",{className:ve("inline-flex items-center gap-1 text-[10px] font-medium px-2 py-0.5 rounded-full",s.cls),children:[s.icon,s.label]})}function H6({source:t}){const e={upload:"📄",dropzone:"📂",email:"📧",url:"🔗"};return o.jsxs("span",{className:"text-xs text-muted-foreground",children:[e[t]??"📄"," ",t]})}function G6(t){return t?t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`:""}function F6({tags:t,activeFilters:e,onToggle:s}){if(!t.length)return null;const i=t.slice(0,3),l=t.length-i.length;return o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[i.map(u=>o.jsx("button",{onClick:d=>s(u,d),className:ve("inline-flex items-center text-[9px] px-1.5 py-0 rounded-full border transition-all",kp(u),e.has(u)&&"ring-1 ring-current font-semibold"),children:u},u)),l>0&&o.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["+",l]})]})}function K6({allTags:t,activeFilters:e,onToggle:s,onClear:i}){return t.length?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground shrink-0",children:[o.jsx(du,{className:"w-3 h-3"}),o.jsx("span",{children:"Filter by tag:"})]}),o.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:t.map(l=>o.jsx("button",{onClick:()=>s(l),className:ve("inline-flex items-center text-[10px] px-2 py-0.5 rounded-full border transition-all",kp(l),e.has(l)?"ring-1 ring-current font-semibold shadow-sm":"opacity-70 hover:opacity-100"),children:l},l))}),e.size>0&&o.jsxs("button",{onClick:i,className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors",children:[o.jsx(zn,{className:"w-3 h-3"}),"Clear"]})]}):null}const Vf=20;function Y6({page:t,total:e,pageSize:s,onPage:i}){const l=Math.max(1,Math.ceil(e/s));if(l<=1&&e<=s)return null;const u=e===0?0:(t-1)*s+1,d=Math.min(t*s,e);return o.jsxs("div",{className:"flex items-center justify-between px-1 pt-2",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:e===0?"No results":`${u}–${d} of ${e}`}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ae,{variant:"outline",size:"sm",className:"h-7 px-2 rounded-lg",onClick:()=>i(t-1),disabled:t<=1,children:o.jsx(Jo,{className:"w-3.5 h-3.5"})}),o.jsxs("span",{className:"text-xs text-muted-foreground px-2",children:["Page ",t," of ",l]}),o.jsx(ae,{variant:"outline",size:"sm",className:"h-7 px-2 rounded-lg",onClick:()=>i(t+1),disabled:t>=l,children:o.jsx(hr,{className:"w-3.5 h-3.5"})})]})]})}function X6({onComposePolicyForDoc:t}){const[e,s]=v.useState([]),[i,l]=v.useState(0),[u,d]=v.useState(1),[h,m]=v.useState(!0),[p,y]=v.useState(!1),[x,w]=v.useState(!1),[j,T]=v.useState(null),[S,_]=v.useState(null),[E,C]=v.useState(null),[A,k]=v.useState(new Set),[M,P]=v.useState([]),[B,R]=v.useState(""),[I,te]=v.useState(""),ie=v.useRef(null),fe=v.useRef(null),Ne=L=>{R(L),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{te(L),d(1)},300)},ye=v.useCallback(async(L=u)=>{if(j===null)return;m(!0);const W=await Ee.getIngestions({page:L,pageSize:Vf,q:I||void 0},j),ee=W?.data?.ingestions??[];s(ee),l(W?.data?.total??0),m(!1),P(le=>[...new Set([...le,...ee.flatMap(q=>q.tags??[])])].sort())},[j,I,u]);v.useEffect(()=>{const L=un();L&&L.auth.getSession().then(({data:W})=>{T(W.session?.access_token??null)})},[]),v.useEffect(()=>{j!==null&&ye(u)},[j,I,u]);const se=v.useMemo(()=>A.size?e.filter(L=>[...A].every(W=>L.tags?.includes(W))):e,[e,A]),V=L=>{k(W=>{const ee=new Set(W);return ee.has(L)?ee.delete(L):ee.add(L),ee}),d(1)},F=async L=>{const W=Array.from(L);if(W.length){w(!0);try{for(const ee of W){ue.info(`Ingesting ${ee.name}…`);const le=await Ee.uploadDocument?.(ee,j);if(le?.success)if(le.ingestion?.status==="duplicate"){const de=le.ingestion.extracted?.original_filename??"a previous upload";ue.warning(`${ee.name} is a duplicate of "${de}" — skipped.`)}else ue.success(`${ee.name} → ${le.ingestion?.status}`);else ue.error(`Failed to ingest ${ee.name}`)}d(1),await ye(1)}finally{w(!1)}}},J=L=>{L.preventDefault(),y(!1),F(L.dataTransfer.files)},ge=async(L,W)=>{W.stopPropagation(),await Ee.rerunIngestion?.(L,j),ue.success("Re-running…"),await ye(u)},ne=async(L,W)=>{if(W.stopPropagation(),!window.confirm("Delete this ingestion record?"))return;await Ee.deleteIngestion?.(L,j),ue.success("Deleted.");const ee=i-1,le=Math.max(1,Math.ceil(ee/Vf)),de=Math.min(u,le);d(de),await ye(de)},D=async(L,W)=>{s(ee=>ee.map(le=>le.id===L?{...le,tags:W}:le)),S?.id===L&&_(ee=>ee&&{...ee,tags:W}),await Ee.updateIngestionTags(L,W,j),P(ee=>[...new Set([...ee,...W])].sort())};return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:o.jsx(Bw,{className:"w-5 h-5 text-primary"})}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold",children:"Funnel"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Document ingestion pipeline"})]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsxs(ae,{variant:"outline",size:"sm",onClick:()=>ye(u),className:"gap-2 rounded-xl",children:[o.jsx(ma,{className:"w-3.5 h-3.5"}),"Refresh"]}),o.jsxs(ae,{size:"sm",onClick:()=>fe.current?.click(),disabled:x,className:"gap-2 rounded-xl",children:[x?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(tm,{className:"w-3.5 h-3.5"}),"Upload"]}),o.jsx("input",{ref:fe,type:"file",multiple:!0,hidden:!0,onChange:L=>L.target.files&&F(L.target.files)})]})]}),o.jsxs("div",{onDragOver:L=>{L.preventDefault(),y(!0)},onDragLeave:()=>y(!1),onDrop:J,onClick:()=>fe.current?.click(),className:ve("rounded-2xl border-2 border-dashed transition-all cursor-pointer flex flex-col items-center justify-center gap-2 py-8",p?"border-primary bg-primary/5 scale-[1.01]":"border-muted-foreground/20 hover:border-primary/50 hover:bg-muted/30"),children:[o.jsx(tm,{className:ve("w-8 h-8 transition-colors",p?"text-primary":"text-muted-foreground/50")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:p?"Drop to ingest":"Drag & drop files here, or click to browse"}),o.jsx("p",{className:"text-xs text-muted-foreground/60",children:".txt, .md, .pdf, .docx — up to 20MB"})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"relative",children:[o.jsx(qC,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),o.jsx("input",{type:"text",value:B,onChange:L=>Ne(L.target.value),placeholder:"Search filename, policy, summary…",className:"w-full pl-9 pr-9 py-2 text-sm rounded-xl border bg-background placeholder:text-muted-foreground/50 outline-none focus:ring-2 focus:ring-primary/30 transition"}),B&&o.jsx("button",{onClick:()=>{R(""),te(""),d(1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors",children:o.jsx(zn,{className:"w-3.5 h-3.5"})})]}),M.length>0&&o.jsx(K6,{allTags:M,activeFilters:A,onToggle:V,onClear:()=>k(new Set)})]}),o.jsx("div",{className:"rounded-2xl border overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"bg-muted/40 border-b",children:o.jsxs("tr",{children:[o.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold text-muted-foreground",children:"File"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Status"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Policy"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Source"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Date"}),o.jsx("th",{className:"px-4 py-3"})]})}),o.jsx("tbody",{className:"divide-y",children:h?o.jsx("tr",{children:o.jsxs("td",{colSpan:6,className:"text-center py-12 text-muted-foreground",children:[o.jsx(rt,{className:"w-5 h-5 animate-spin mx-auto mb-2"}),"Loading…"]})}):se.length===0?o.jsx("tr",{children:o.jsxs("td",{colSpan:6,className:"text-center py-16 text-muted-foreground",children:[o.jsx(Vm,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),o.jsx("p",{className:"text-sm",children:I||A.size>0?"No documents match your search.":"No ingestions yet — upload a document above."}),(I||A.size>0)&&o.jsx("button",{className:"mt-2 text-xs text-primary hover:underline",onClick:()=>{R(""),te(""),k(new Set),d(1)},children:"Clear filters"})]})}):se.map(L=>o.jsxs("tr",{onClick:()=>_(L),className:ve("cursor-pointer transition-colors",L.status==="processing"?"animate-pulse bg-blue-500/5 hover:bg-blue-500/10":"hover:bg-muted/30"),children:[o.jsxs("td",{className:"px-5 py-3.5",children:[o.jsx("div",{className:"font-medium text-sm truncate max-w-[220px]",title:L.filename,children:L.filename}),L.status==="duplicate"?o.jsxs("div",{className:"text-xs text-violet-500/80 truncate max-w-[220px]",children:["↳ ",L.extracted?.original_filename??"previously processed"]}):L.file_size&&o.jsx("div",{className:"text-xs text-muted-foreground",children:G6(L.file_size)}),o.jsx(F6,{tags:L.tags??[],activeFilters:A,onToggle:(W,ee)=>{ee.stopPropagation(),V(W)}})]}),o.jsx("td",{className:"px-4 py-3.5",children:o.jsx(q6,{status:L.status})}),o.jsx("td",{className:"px-4 py-3.5",children:L.policy_name?o.jsx(Mt,{variant:"secondary",className:"text-[10px]",children:L.policy_name}):o.jsx("span",{className:"text-muted-foreground/50 text-xs",children:"—"})}),o.jsx("td",{className:"px-4 py-3.5",children:o.jsx(H6,{source:L.source})}),o.jsx("td",{className:"px-4 py-3.5 text-xs text-muted-foreground whitespace-nowrap",children:new Date(L.created_at).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"})}),o.jsx("td",{className:"px-4 py-3.5",children:o.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[o.jsx("button",{title:"View Processing Trace",onClick:W=>{W.stopPropagation(),C(L)},className:"text-muted-foreground hover:text-emerald-500 p-1 transition-colors",children:o.jsx(Io,{className:"w-3.5 h-3.5"})}),o.jsx("button",{title:"Re-run",onClick:W=>ge(L.id,W),className:"text-muted-foreground hover:text-foreground p-1 transition-colors",children:o.jsx(ma,{className:"w-3.5 h-3.5"})}),o.jsx("button",{title:"Delete",onClick:W=>ne(L.id,W),className:"text-muted-foreground hover:text-destructive p-1 transition-colors",children:o.jsx(el,{className:"w-3.5 h-3.5"})}),o.jsx(hr,{className:"w-3.5 h-3.5 text-muted-foreground/40"})]})})]},L.id))})]})}),o.jsx(Y6,{page:u,total:i,pageSize:Vf,onPage:L=>d(L)}),S&&o.jsx(V6,{ingestion:S,onClose:()=>_(null),onTagsChange:L=>D(S.id,L),onRerun:async()=>{await Ee.rerunIngestion?.(S.id,j),await ye(u),_(null),ue.success("Re-running ingestion…")},onComposePolicy:t?L=>{_(null),t(L)}:void 0,onManualMatch:async({policyId:L,learn:W,rerun:ee,allowSideEffects:le})=>{const de=await Ee.matchIngestionToPolicy(S.id,{policyId:L,learn:W,rerun:ee,allowSideEffects:le},j);if(de?.error){const pe=typeof de.error=="string"?de.error:de.error.message;throw new Error(pe||"Failed to match ingestion to policy.")}const q=de?.data?.ingestion;if(!q)throw new Error("Match succeeded but updated ingestion payload is missing.");q&&(s(pe=>pe.map(oe=>oe.id===q.id?q:oe)),_(q)),await ye(u),ee?ue.success(W?"Policy matched, learned, and re-run started.":"Policy matched and re-run started."):ue.success(W?"Policy match saved and learned.":"Policy match saved.")}}),E&&o.jsx($6,{ingestion:E,onClose:()=>C(null)})]})}function W6({activeSessionId:t,onSelectSession:e,refreshTrigger:s}){const[i,l]=v.useState([]),[u,d]=v.useState(!0),h=v.useCallback(async()=>{const y=un();if(!y)return null;const{data:x}=await y.auth.getSession();return x.session?.access_token??null},[]),m=v.useCallback(async()=>{try{const y=await h(),x=await Ee.getChatSessions(y);x.data?.success&&l(x.data.sessions)}catch(y){console.error("Failed to fetch sessions",y)}finally{d(!1)}},[h]);v.useEffect(()=>{m()},[m,s]);const p=async(y,x)=>{y.stopPropagation();try{const w=await un();if(!w)return;const{error:j}=await w.from("chat_sessions").delete().eq("id",x);j||(l(T=>T.filter(S=>S.id!==x)),t===x&&e(null))}catch(w){console.error(w)}};return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx("div",{className:"p-3 border-b border-border bg-surface/15",children:o.jsxs("button",{onClick:()=>e(null),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary/10 hover:bg-primary/20 text-primary rounded-xl transition-all font-semibold text-sm border border-primary/20 cursor-pointer",children:[o.jsx(Ja,{size:16}),"New Chat"]})}),o.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1 scrollbar-on-hover",children:u?o.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"Loading..."}):i.length===0?o.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[o.jsx(cu,{size:24,className:"mx-auto opacity-20 mb-2"}),o.jsx("p",{className:"text-xs",children:"No chat history"})]}):i.map(y=>o.jsxs("div",{onClick:()=>e(y.id),className:`group flex items-center justify-between px-3 py-3 rounded-lg cursor-pointer transition-all text-sm ${t===y.id?"bg-primary/15 text-foreground ring-1 ring-primary/30 font-medium":"text-muted-foreground hover:bg-surface/50 hover:text-foreground"}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5 overflow-hidden",children:[o.jsx(cu,{size:14,className:t===y.id?"text-primary":"opacity-50"}),o.jsx("span",{className:"truncate",children:y.title})]}),o.jsx("button",{onClick:x=>p(x,y.id),className:"opacity-0 group-hover:opacity-100 p-1.5 hover:bg-destructive/10 hover:text-destructive rounded transition-all",children:o.jsx(el,{size:12})})]},y.id))})]})}function J6({message:t}){const e=t.role==="user",s=i=>i.split(`
112
+ `);C=P.pop()||"";for(const B of P){const R=B.trim();if(!(!R||!R.startsWith("data: ")))try{const I=JSON.parse(R.substring(6));I.type==="done"?I.data==="success"&&(A=!0):I.data&&p(te=>[...te,I.data])}catch{}}}if(A)p(k=>[...k,"","═".repeat(50),"✅ FOUNDATION UPDATED","","✓ Database schema synchronized","✓ API contracts verified","","System will reload to apply changes...","═".repeat(50)]),setTimeout(()=>{window.location.reload()},2e3);else throw new Error("Migration completed with errors.")}catch(S){console.error(S),p(_=>[..._,"",`❌ FATAL ERROR: ${S instanceof Error?S.message:String(S)}`]),ue.error("Migration interrupted. Consult system logs.")}finally{h(!1)}};return o.jsx(ei,{open:t,onOpenChange:S=>!d&&e(S),children:o.jsx(ti,{className:"max-h-[90vh] sm:max-w-4xl overflow-y-auto border-none bg-background/95 backdrop-blur-2xl shadow-2xl p-0 gap-0 selection:bg-primary/20",children:o.jsxs("div",{className:"bg-gradient-to-br from-primary/5 via-transparent to-transparent",children:[o.jsx(fr,{className:"p-8 pb-4",children:o.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[o.jsx("div",{className:"w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center",children:o.jsx(hu,{className:"h-6 w-6 text-primary"})}),o.jsxs("div",{children:[o.jsx(mr,{className:"text-2xl font-black tracking-tight",children:"Database Setup Required"}),o.jsxs(tl,{className:"text-xs font-bold uppercase tracking-[0.2em] opacity-60",children:["Foundational Registry Sync • ",s.appVersion]})]})]})}),o.jsxs("div",{className:"px-8 pb-8 space-y-6",children:[o.jsxs(jn,{className:"bg-muted/40 border-none rounded-2xl p-4",children:[o.jsx(Im,{className:"h-4 w-4 text-primary"}),o.jsxs(_n,{className:"text-xs font-medium leading-relaxed",children:["Your application requires a database schema update to enable new features like ",o.jsx("strong",{children:"Enhanced TTS Engine"})," and ",o.jsx("strong",{children:"Real-time Intelligence Streaming"}),". Existing data remains untouched."]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsx("div",{className:"space-y-4",children:o.jsxs("div",{className:"rounded-2xl border bg-card/50 shadow-sm p-6 space-y-4",children:[o.jsx("h3",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground",children:"Security Credentials"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Je,{htmlFor:"project-id",className:"text-[10px] uppercase tracking-widest font-black opacity-60",children:"Project Identity"}),o.jsx(_e,{id:"project-id",value:j,disabled:!0,readOnly:!0,className:"h-10 bg-muted/50 border-none font-mono text-xs rounded-xl"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx(Je,{htmlFor:"access-token",className:"text-[10px] uppercase tracking-widest font-black opacity-60",children:"Personal Access Token"}),o.jsxs("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-[10px] font-black tracking-widest text-primary hover:underline flex items-center gap-1",children:["GENERATE ",o.jsx(Uw,{className:"h-2.5 w-2.5"})]})]}),o.jsx(_e,{id:"access-token",type:"password",placeholder:"sbp_...",value:y,onChange:S=>x(S.target.value),disabled:d,className:"h-10 bg-background border-border/40 focus:ring-primary/20 rounded-xl font-mono text-xs"})]}),o.jsx(ae,{onClick:T,disabled:d||!y,className:"w-full h-11 rounded-xl bg-primary text-primary-foreground font-black text-[10px] uppercase tracking-[0.2em] shadow-lg shadow-primary/20 hover:scale-[1.02] active:scale-[0.98] transition-all",children:d?o.jsxs(o.Fragment,{children:[o.jsx(rt,{className:"mr-2 h-4 w-4 animate-spin"}),"Deploying..."]}):o.jsxs(o.Fragment,{children:[o.jsx(ya,{className:"mr-2 h-4 w-4"}),"Initialize Protocol"]})})]})]})}),o.jsxs("div",{className:"flex flex-col rounded-2xl border bg-zinc-950/95 text-zinc-400 font-mono text-[11px] p-5 shadow-inner min-h-[300px] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-4 shrink-0",children:[o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-red-500/20"}),o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-amber-500/20"}),o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-emerald-500/20"})]}),o.jsx("span",{className:"text-[9px] font-black uppercase tracking-widest opacity-40 ml-2",children:"Foundation Terminal"})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar",children:[m.length===0?o.jsxs("div",{className:"text-zinc-700 italic flex flex-col items-center justify-center h-full opacity-50",children:[o.jsx(Io,{className:"h-8 w-8 mb-2"}),o.jsx("span",{children:"Awaiting synchronization..."})]}):m.map((S,_)=>o.jsxs("div",{className:ve("mb-1.5 leading-relaxed break-words",S.includes("✅")||S.includes("success")?"text-emerald-400":S.includes("❌")||S.includes("Error")?"text-red-400 font-bold":S.includes("🚀")||S.includes("[System]")?"text-primary":""),children:[o.jsx("span",{className:"opacity-30 mr-2",children:_+1}),S]},_)),o.jsx("div",{ref:w})]})]})]})]}),o.jsx(nr,{className:"p-8 pt-0 flex-col sm:flex-row gap-3",children:o.jsxs("div",{className:"flex gap-3 w-full",children:[o.jsxs(ae,{type:"button",variant:"secondary",onClick:()=>u(1),disabled:d,className:"flex-1 h-11 rounded-xl font-black text-[10px] uppercase tracking-widest",children:[o.jsx(Qo,{className:"h-4 w-4 mr-2 opacity-60"}),"Snooze 1h"]}),o.jsxs(ae,{type:"button",variant:"secondary",onClick:()=>u(24),disabled:d,className:"flex-1 h-11 rounded-xl font-black text-[10px] uppercase tracking-widest",children:[o.jsx(zw,{className:"h-4 w-4 mr-2 opacity-60"}),"Tomorrow"]})]})})]})})})}const R6=[{id:"bay-area-utilities",name:"Bay Area Utilities",description:"PG&E, Recology, EBMUD, and SCE bill handling",policies:4,tags:["utilities","california"]},{id:"freelancer-tax",name:"Freelancer Tax Pack",description:"1099-NEC, W-9, invoices, and estimated taxes",policies:6,tags:["finance","tax"]},{id:"medical-records",name:"Medical Records",description:"EOB, lab results, prescription receipts",policies:5,tags:["health","insurance"]},{id:"legal-docs",name:"Legal Documents",description:"Contracts, notices, deeds, and court documents",policies:3,tags:["legal","priority"]}];function O6({initialCompose:t,onInitialConsumed:e}){const[s,i]=v.useState([]),[l,u]=v.useState(!0),[d,h]=v.useState(""),[m,p]=v.useState(!1),[y,x]=v.useState(null),[w,j]=v.useState(!1),[T,S]=v.useState(!1),[_,E]=v.useState(null),[C,A]=v.useState("policies"),[k,M]=v.useState([]),[P,B]=v.useState(""),[R,I]=v.useState(""),[te,ie]=v.useState(null),[fe,Ne]=v.useState(null),[ye,se]=v.useState(null),[V,F]=v.useState(!1),[J,ge]=v.useState({name:"",description:"",keywords:"",matchStrategy:"ANY",actions:[{type:"copy",destination:"",filename:"",columns:[],spreadsheet_id:"",range:""}],tags:"",priority:100}),[ne,D]=v.useState(!1),L=v.useCallback(async()=>{u(!0);const U=await Ee.getPolicies?.(te);U?.data?.policies&&i(U.data.policies),u(!1)},[te]),W=v.useCallback(async()=>{try{const re=(await Ee.getSDKChatProviders?.())?.data?.providers??[];M(re),re.length>0&&!P&&(B(re[0].provider),I(re[0].models?.[0]?.id??""))}catch{}},[P]);v.useEffect(()=>{const U=un();U&&U.auth.getSession().then(({data:re})=>{ie(re.session?.access_token??null)})},[]),v.useEffect(()=>{L(),W()},[L,W]),v.useEffect(()=>{t&&(h(t),e?.())},[t,e]);const ee=async()=>{if(d.trim()){p(!0),x(null);try{const U=await Ee.synthesizePolicy?.({description:d,provider:P||void 0,model:R||void 0},te);if(U?.data?.policy){x(U.data.policy),j(!1);const re=U.data.warning;re?ue.warning(re):ue.success("Policy synthesized! Review and save below.")}else ue.error(U?.data?.error??"Synthesis failed.")}catch{ue.error("LLM synthesis failed.")}finally{p(!1)}}},le=async U=>{S(!0);try{await Ee.savePolicy?.(U,te),ue.success(`Policy "${U.metadata.name}" saved.`),x(null),h(""),await L()}catch{ue.error("Failed to save policy.")}finally{S(!1)}},de=async U=>{window.confirm(`Delete policy "${U}"?`)&&(await Ee.deletePolicy?.(U,te),ue.success("Policy deleted."),await L())},q=async U=>{i(re=>re.map(De=>De.metadata.id===U.metadata.id?{...De,metadata:{...De.metadata,enabled:!De.metadata.enabled}}:De));try{await Ee.patchPolicy?.(U.metadata.id,{enabled:!U.metadata.enabled},te)}catch{ue.error("Failed to toggle policy."),await L()}},pe=U=>{Ne(U.metadata.id),se({name:U.metadata.name,description:U.metadata.description,tags:(U.metadata.tags??[]).join(", "),priority:U.metadata.priority})},oe=()=>{Ne(null),se(null)},ze=async U=>{if(ye)try{await Ee.patchPolicy?.(U,{name:ye.name,description:ye.description,tags:ye.tags.split(",").map(re=>re.trim()).filter(Boolean),priority:ye.priority},te),ue.success("Policy updated."),Ne(null),se(null),await L()}catch{ue.error("Failed to save edits.")}},Be=U=>{h(U.metadata.description),A("policies"),ue.success("Description pre-filled — edit and click ✨ to re-synthesize.")},kt=async()=>{await Ee.reloadPolicies?.(te),await L(),ue.success("Policies reloaded.")},et=(U,re,De)=>{ge(qe=>{const ft=qe.actions.map((Zt,Ve)=>Ve===U?{...Zt,[re]:De}:Zt);return{...qe,actions:ft}})},ce=()=>{ge(U=>({...U,actions:[...U.actions,{type:"copy",destination:"",filename:"",columns:[],spreadsheet_id:"",range:""}]}))},Fe=U=>{ge(re=>({...re,actions:re.actions.filter((De,qe)=>qe!==U)}))},he=U=>U.type==="append_to_google_sheet"&&!U.spreadsheet_id?.trim(),Me=J.actions.some(he),at=async()=>{if(!J.name.trim())return;const U=J.actions.findIndex(he);if(U!==-1){ue.error(`Action #${U+1}: "Append to Google Sheet" requires Spreadsheet ID or Google Sheet URL.`);return}D(!0);try{const re=J.name.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),De=J.keywords.split(",").map(Ve=>Ve.trim()).filter(Boolean),qe=J.tags.split(",").map(Ve=>Ve.trim()).filter(Boolean),ft=J.actions.filter(Ve=>Ve.type==="copy_to_gdrive"||Ve.type==="auto_rename"||Ve.type==="append_to_google_sheet"||Ve.destination.trim()).map(Ve=>{const en={type:Ve.type};if(Ve.type==="copy")en.destination=Ve.destination,Ve.filename&&(en.filename=Ve.filename);else if(Ve.type==="rename")en.destination=Ve.destination;else if(Ve.type!=="auto_rename"){if(Ve.type==="copy_to_gdrive")Ve.destination.trim()&&(en.destination=Ve.destination.trim()),Ve.filename&&(en.filename=Ve.filename);else if(Ve.type==="log_csv")en.path=Ve.destination;else if(Ve.type==="append_to_google_sheet"){const ll=Ve.spreadsheet_id?.trim();ll&&(en.spreadsheet_id=ll);const Ms=Ve.range?.trim();Ms&&(en.range=Ms);const Kt=(Ve.columns??[]).map(Wn=>Wn.trim()).filter(Boolean);Kt.length>0&&(en.columns=Kt)}}return en}),Zt={metadata:{id:re,name:J.name.trim(),description:J.description.trim(),priority:J.priority,tags:qe,enabled:!0},spec:{match:{strategy:J.matchStrategy,conditions:De.length>0?[{type:"keyword",value:De}]:[{type:"keyword",value:[]}]},extract:[],actions:ft}};await Ee.savePolicy?.(Zt,te),ue.success(`Policy "${Zt.metadata.name}" created.`),F(!1),ge({name:"",description:"",keywords:"",matchStrategy:"ANY",actions:[{type:"copy",destination:"",filename:"",columns:[],spreadsheet_id:"",range:""}],tags:"",priority:100}),await L()}catch{ue.error("Failed to create policy.")}finally{D(!1)}},Ut=U=>{if(U.type==="append_to_google_sheet"){const re=U.spreadsheet_id?.trim()||U.spreadsheet_url?.trim()||"",De=U.range?.trim()||"";return re&&De?`${re} (${De})`:re||De}return U.type==="log_csv"?U.path?.trim()||"":U.destination?.trim()||U.pattern?.trim()||""},Xn=(U,re)=>{x(De=>{if(!De)return De;const qe=(De.spec.actions??[]).map((ft,Zt)=>Zt===U?{...ft,...re}:ft);return{...De,spec:{...De.spec,actions:qe}}})},jr=(U=>{if(!U)return[];const re=[];U.metadata.name?.trim()||re.push("Policy name is missing."),U.metadata.id?.trim()||re.push("Policy id is missing.");const De=U.spec.actions??[];return De.length===0&&re.push("At least one action is required."),De.forEach((qe,ft)=>{qe.type==="append_to_google_sheet"&&(qe.spreadsheet_id?.trim()||qe.spreadsheet_url?.trim()||re.push(`Action #${ft+1} append_to_google_sheet is missing spreadsheet_id / URL.`)),qe.type==="copy"&&!qe.destination?.trim()&&re.push(`Action #${ft+1} copy is missing destination.`),qe.type==="rename"&&!(qe.pattern?.trim()||qe.destination?.trim())&&re.push(`Action #${ft+1} rename is missing pattern.`)}),re})(y),Uu=!!y&&jr.length===0&&!T;return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-10 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex items-end justify-between",children:[o.jsxs("div",{children:[o.jsxs("h1",{className:"text-3xl font-black tracking-tight flex items-center gap-3",children:[o.jsx(Hw,{className:"w-8 h-8 text-primary"}),"Policy Engine"]}),o.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Define automation rules that govern how Folio handles your documents."})]}),o.jsxs(ae,{variant:"outline",size:"sm",onClick:kt,className:"gap-2 rounded-xl",children:[o.jsx(ma,{className:"w-4 h-4"}),"Reload"]})]}),o.jsx("div",{className:"flex gap-1 p-1 rounded-2xl bg-muted/50 border w-fit",children:["policies","packs"].map(U=>o.jsx("button",{onClick:()=>A(U),className:ve("px-5 py-2 rounded-xl text-xs font-black uppercase tracking-widest transition-all",C===U?"bg-background shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"),children:U==="policies"?"Active Policies":"Policy Packs"},U))}),C==="policies"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-2xl border bg-card/60 backdrop-blur-sm p-6 shadow-sm space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx(Cs,{className:"w-4 h-4 text-primary"}),o.jsx("h2",{className:"text-sm font-black uppercase tracking-widest",children:"Magic Composer"})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Describe a rule in plain English. Click ✨ to generate the policy automatically."}),k.length>0&&o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsx(Bm,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),o.jsx("select",{value:`${P}::${R}`,onChange:U=>{const[re,De]=U.target.value.split("::");B(re),I(De)},className:"text-xs rounded-lg border border-border/40 bg-background px-2 py-1 text-foreground flex-1 max-w-xs",children:k.flatMap(U=>(U.models??[]).map(re=>o.jsxs("option",{value:`${U.provider}::${re.id}`,children:[U.provider," / ",re.id]},`${U.provider}::${re.id}`)))}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:"for synthesis"})]}),o.jsxs("div",{className:"flex gap-3 items-start",children:[o.jsx(Ym,{placeholder:"e.g. If I get a bill from Tesla, move it to /Car/ folder and log the amount to my CSV…",value:d,onChange:U=>h(U.target.value),className:"flex-1 min-h-[80px] resize-none rounded-xl border-border/40 bg-background text-sm",onKeyDown:U=>{U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&ee()}}),o.jsx(ae,{onClick:ee,disabled:m||!d.trim(),className:ve("h-10 w-10 p-0 rounded-xl flex items-center justify-center transition-all","bg-primary text-primary-foreground shadow-lg shadow-primary/20","hover:scale-105 active:scale-95"),title:"Synthesize policy with AI",children:m?o.jsx(rt,{className:"w-4 h-4 animate-spin"}):o.jsx(Cs,{className:"w-4 h-4"})})]}),y&&o.jsxs("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-4 space-y-3 animate-in slide-in-from-bottom-2 duration-300",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("p",{className:"font-black text-sm",children:y.metadata.name}),o.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:y.metadata.description})]}),o.jsxs(Mt,{variant:"outline",className:"text-[10px] uppercase font-bold",children:["Priority ",y.metadata.priority]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 text-xs text-muted-foreground",children:[o.jsxs("div",{className:"rounded-lg bg-muted/60 p-2",children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] mb-1 text-foreground",children:"Match"}),o.jsxs("div",{className:"space-y-1",children:[y.spec.match.conditions.length===0&&o.jsx("div",{children:"—"}),y.spec.match.conditions.map((U,re)=>o.jsxs("div",{children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:U.type})," ",Array.isArray(U.value)?U.value.join(", "):U.value]},`${U.type}-${re}`))]})]}),o.jsxs("div",{className:"rounded-lg bg-muted/60 p-2",children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] mb-1 text-foreground",children:"Extract"}),o.jsxs("div",{className:"space-y-1",children:[(y.spec.extract?.length??0)===0&&o.jsx("div",{children:"—"}),y.spec.extract?.map(U=>o.jsxs("div",{children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:U.key})," ","(",U.type,")",U.required?" *":""]},U.key))]})]}),o.jsxs("div",{className:"rounded-lg bg-muted/60 p-2",children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] mb-1 text-foreground",children:"Actions"}),o.jsxs("div",{className:"space-y-2",children:[(y.spec.actions?.length??0)===0&&o.jsx("div",{children:"—"}),y.spec.actions?.map((U,re)=>o.jsxs("div",{className:"rounded-md border border-border/50 bg-background/80 p-2 space-y-1.5",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:U.type})," ",Ut(U)]}),U.type==="copy_to_gdrive"&&o.jsx(_e,{value:U.destination??"",onChange:De=>Xn(re,{destination:De.target.value}),placeholder:"Google Drive folder ID",className:"h-7 text-[11px] rounded-lg font-mono"}),U.type==="append_to_google_sheet"&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(_e,{value:U.spreadsheet_id??U.spreadsheet_url??"",onChange:De=>Xn(re,{spreadsheet_id:De.target.value,spreadsheet_url:void 0}),placeholder:"Spreadsheet ID or URL",className:"h-7 text-[11px] rounded-lg font-mono"}),o.jsx(_e,{value:U.range??"",onChange:De=>Xn(re,{range:De.target.value}),placeholder:"Optional range (e.g. Sheet1!A:Z)",className:"h-7 text-[11px] rounded-lg font-mono"})]})]},`${U.type}-${re}`))]})]})]}),jr.length>0?o.jsx(jn,{className:"rounded-xl border-red-200 bg-red-50",children:o.jsxs(_n,{className:"text-xs text-red-700",children:[o.jsx("div",{className:"font-semibold mb-1",children:"Fix before saving:"}),o.jsx("div",{className:"space-y-0.5",children:jr.map((U,re)=>o.jsx("div",{children:U},`synth-issue-${re}`))})]})}):o.jsx("div",{className:"text-[11px] text-emerald-700 font-semibold",children:"Policy looks valid for save."}),o.jsx("div",{className:"flex gap-2",children:o.jsx(ae,{type:"button",size:"sm",variant:"outline",onClick:()=>j(U=>!U),className:"h-7 px-2 rounded-lg text-[10px] uppercase tracking-widest",children:w?"Hide JSON":"Show JSON"})}),w&&o.jsx("pre",{className:"rounded-lg border border-border/40 bg-background p-3 text-[11px] overflow-auto max-h-72 whitespace-pre-wrap font-mono",children:JSON.stringify(y,null,2)}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx(ae,{size:"sm",onClick:()=>le(y),disabled:!Uu,className:"flex-1 h-8 rounded-xl font-black text-[10px] uppercase tracking-widest",children:T?o.jsx(rt,{className:"w-3 h-3 animate-spin"}):"Save Policy"}),o.jsx(ae,{size:"sm",variant:"outline",onClick:()=>{x(null),j(!1)},className:"h-8 px-3 rounded-xl",children:"Discard"})]})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("h2",{className:"text-xs font-black uppercase tracking-widest text-muted-foreground",children:["Active Policies (",s.length,")"]}),o.jsx(ae,{size:"sm",variant:V?"secondary":"outline",onClick:()=>F(U=>!U),className:"h-7 px-3 rounded-xl gap-1.5 text-[10px] font-black uppercase tracking-widest",children:V?o.jsxs(o.Fragment,{children:[o.jsx(zn,{className:"w-3 h-3"}),"Cancel"]}):o.jsxs(o.Fragment,{children:[o.jsx(hu,{className:"w-3 h-3"}),"Quick Create"]})})]}),V&&o.jsxs("div",{className:"rounded-2xl border border-primary/20 bg-primary/5 p-5 space-y-4 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(hu,{className:"w-3.5 h-3.5 text-primary"}),o.jsx("span",{className:"text-xs font-black uppercase tracking-widest text-primary",children:"Quick Create Policy"})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"col-span-2 space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Name *"}),o.jsx(_e,{placeholder:"e.g. Tesla Invoice Handler",value:J.name,onChange:U=>ge({...J,name:U.target.value}),className:"h-8 text-sm rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"col-span-2 space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Description"}),o.jsx(_e,{placeholder:"What does this policy do?",value:J.description,onChange:U=>ge({...J,description:U.target.value}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Match Keywords"}),o.jsx(_e,{placeholder:"tesla, invoice, PG&E (comma-sep)",value:J.keywords,onChange:U=>ge({...J,keywords:U.target.value}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Match Strategy"}),o.jsxs("select",{value:J.matchStrategy,onChange:U=>ge({...J,matchStrategy:U.target.value}),className:"h-8 w-full text-xs rounded-xl border border-border/40 bg-background px-3 text-foreground",children:[o.jsx("option",{value:"ANY",children:"ANY keyword matches"}),o.jsx("option",{value:"ALL",children:"ALL keywords match"})]})]}),o.jsxs("div",{className:"col-span-2 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Actions"}),o.jsxs("button",{type:"button",onClick:ce,className:"flex items-center gap-1 text-[10px] font-bold text-primary hover:text-primary/80 transition-colors",children:[o.jsx(Ja,{className:"w-3 h-3"}),"Add Action"]})]}),o.jsx("div",{className:"space-y-2",children:J.actions.map((U,re)=>{const De=!U.filename||U.filename===""?"original":U.filename==="auto"?"auto":"custom";return o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-2 items-start",children:[o.jsxs("select",{value:U.type,onChange:qe=>et(re,"type",qe.target.value),className:"h-8 text-xs rounded-xl border border-border/40 bg-background px-2 text-foreground w-full",children:[o.jsx("option",{value:"copy",children:"Copy to folder"}),o.jsx("option",{value:"rename",children:"Rename file (Pattern)"}),o.jsx("option",{value:"log_csv",children:"Log to CSV"}),o.jsx("option",{value:"copy_to_gdrive",children:"Copy to Google Drive"}),o.jsx("option",{value:"append_to_google_sheet",children:"Append to Google Sheet"})]}),o.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[U.type!=="append_to_google_sheet"&&o.jsx(_e,{placeholder:U.type==="copy"?"/Car/":U.type==="copy_to_gdrive"?"Folder ID (empty = My Drive root)":U.type==="rename"?"Tesla-{date}":"/logs/invoices.csv",value:U.destination,onChange:qe=>et(re,"destination",qe.target.value),className:"h-8 text-xs rounded-xl border-border/40 bg-background font-mono flex-1 min-w-0"}),J.actions.length>1&&o.jsx("button",{type:"button",onClick:()=>Fe(re),className:"text-muted-foreground hover:text-destructive transition-colors shrink-0 p-1",children:o.jsx(zn,{className:"w-3.5 h-3.5"})})]})]}),(U.type==="copy"||U.type==="copy_to_gdrive")&&o.jsxs("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-2 items-center",children:[o.jsx("div",{"aria-hidden":"true"}),o.jsxs("div",{className:"flex gap-2 items-center min-w-0",children:[o.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:"Filename:"}),o.jsxs("select",{value:De,onChange:qe=>{const ft=qe.target.value;ft==="original"?et(re,"filename",""):ft==="auto"?et(re,"filename","auto"):et(re,"filename","{date}_{issuer}_{document_type}")},className:"h-7 text-xs rounded-lg border border-border/40 bg-background px-2 text-foreground shrink-0",children:[o.jsx("option",{value:"original",children:"Keep original"}),o.jsx("option",{value:"auto",children:"Smart rename (AI)"}),o.jsx("option",{value:"custom",children:"Custom pattern"})]}),De==="custom"&&o.jsx(_e,{value:U.filename,onChange:qe=>et(re,"filename",qe.target.value),placeholder:"{date}_{issuer}_{document_type}",className:"h-7 text-xs rounded-lg border-border/40 bg-background font-mono flex-1 min-w-0"})]})]}),U.type==="append_to_google_sheet"&&o.jsxs("div",{className:"grid grid-cols-[9rem_minmax(0,1fr)] gap-2",children:[o.jsx("div",{"aria-hidden":"true"}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx(_e,{placeholder:"Spreadsheet ID or Google Sheet URL",value:U.spreadsheet_id||"",onChange:qe=>et(re,"spreadsheet_id",qe.target.value),className:"h-7 text-xs rounded-lg flex-1"}),o.jsx(_e,{placeholder:"Optional tab/range (e.g. Sheet1!A:F)",value:U.range||"",onChange:qe=>et(re,"range",qe.target.value),className:"h-7 text-xs rounded-lg w-32"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 p-2 rounded-lg border border-border/40 bg-muted/20",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Je,{className:"text-[10px] uppercase font-bold text-muted-foreground",children:"Columns Mapping (A, B, C...)"}),o.jsxs(ae,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-[10px] px-2 py-0",onClick:()=>{const qe=[...U.columns||[],""];et(re,"columns",qe)},children:[o.jsx(Ja,{className:"w-3 h-3 mr-1"})," Add Col"]})]}),(U.columns||[]).map((qe,ft)=>o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-[10px] font-mono text-muted-foreground w-4 flex-shrink-0 text-center",children:String.fromCharCode(65+ft)}),o.jsx(_e,{placeholder:"e.g. {Date} or Static Text",value:qe,onChange:Zt=>{const Ve=[...U.columns||[]];Ve[ft]=Zt.target.value,et(re,"columns",Ve)},className:"h-7 text-xs rounded-lg font-mono flex-1"}),o.jsx("button",{type:"button",onClick:()=>{const Zt=(U.columns||[]).filter((Ve,en)=>en!==ft);et(re,"columns",Zt)},className:"text-muted-foreground hover:text-destructive p-1",children:o.jsx(zn,{className:"w-3 h-3"})})]},ft)),(!U.columns||U.columns.length===0)&&o.jsx("div",{className:"text-[10px] text-muted-foreground italic text-center py-1",children:"No explicit mapping provided. Folio will auto-map by reading header row from the sheet template."})]})]})]})]},re)})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Tags"}),o.jsx(_e,{placeholder:"finance, cars (comma-sep)",value:J.tags,onChange:U=>ge({...J,tags:U.target.value}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Je,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:"Priority"}),o.jsx(_e,{type:"number",min:1,max:999,value:J.priority,onChange:U=>ge({...J,priority:Number(U.target.value)}),className:"h-8 text-xs rounded-xl border-border/40 bg-background"})]})]}),Me&&o.jsx("p",{className:"text-[10px] text-destructive",children:'"Append to Google Sheet" actions require a Spreadsheet ID or Google Sheet URL.'}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx(ae,{size:"sm",onClick:at,disabled:ne||!J.name.trim()||Me,className:"flex-1 h-8 rounded-xl font-black text-[10px] uppercase tracking-widest gap-1.5",children:ne?o.jsx(rt,{className:"w-3 h-3 animate-spin"}):o.jsxs(o.Fragment,{children:[o.jsx(Ja,{className:"w-3 h-3"}),"Create Policy"]})}),o.jsx(ae,{size:"sm",variant:"outline",onClick:()=>F(!1),className:"h-8 px-3 rounded-xl",children:"Cancel"})]})]}),l?o.jsxs("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[o.jsx(rt,{className:"w-6 h-6 animate-spin mr-3"}),"Loading policies..."]}):s.length===0?o.jsxs(jn,{className:"rounded-2xl border-dashed",children:[o.jsx(Im,{className:"h-4 w-4"}),o.jsx(_n,{className:"text-sm",children:"No policies yet. Use the Magic Composer above to create your first one."})]}):o.jsx("div",{className:"space-y-2",children:s.map(U=>o.jsxs("div",{className:ve("rounded-2xl border bg-card/50 shadow-sm overflow-hidden transition-all",U.metadata.enabled===!1&&"opacity-60"),children:[o.jsxs("div",{className:"flex items-center gap-3 px-5 py-4",children:[o.jsx("button",{title:U.metadata.enabled===!1?"Enable policy":"Disable policy",onClick:()=>q(U),className:"shrink-0 text-muted-foreground hover:text-foreground transition-colors",children:U.metadata.enabled===!1?o.jsx(lA,{className:"w-5 h-5 text-muted-foreground"}):o.jsx(uA,{className:"w-5 h-5 text-primary"})}),o.jsx("div",{className:"flex-1 min-w-0",children:fe===U.metadata.id&&ye?o.jsxs("div",{className:"space-y-2",onClick:re=>re.stopPropagation(),children:[o.jsx(_e,{value:ye.name,onChange:re=>se({...ye,name:re.target.value}),placeholder:"Policy name",className:"h-7 text-sm font-semibold"}),o.jsx(_e,{value:ye.description,onChange:re=>se({...ye,description:re.target.value}),placeholder:"Description",className:"h-7 text-xs"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(_e,{value:ye.tags,onChange:re=>se({...ye,tags:re.target.value}),placeholder:"Tags (comma-separated)",className:"h-7 text-xs flex-1"}),o.jsx(_e,{type:"number",value:ye.priority,onChange:re=>se({...ye,priority:Number(re.target.value)}),placeholder:"Priority",className:"h-7 text-xs w-20",min:1,max:999})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"font-bold text-sm truncate",children:U.metadata.name}),o.jsxs(Mt,{variant:"outline",className:"text-[9px] shrink-0",children:["P",U.metadata.priority]}),(U.metadata.learning_examples??0)>0&&o.jsxs(Mt,{variant:"secondary",className:"text-[9px] shrink-0",children:["Learned ",U.metadata.learning_examples]}),U.metadata.tags?.map(re=>o.jsxs(Mt,{variant:"secondary",className:"text-[9px] gap-1 shrink-0",children:[o.jsx(du,{className:"w-2.5 h-2.5"}),re]},re))]}),o.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:U.metadata.description})]})}),o.jsx("div",{className:"flex items-center gap-1 shrink-0",children:fe===U.metadata.id?o.jsxs(o.Fragment,{children:[o.jsx(ae,{size:"sm",variant:"default",className:"h-7 px-2 text-xs",onClick:()=>ze(U.metadata.id),children:"Save"}),o.jsx(ae,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:oe,children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{title:"Edit metadata",onClick:()=>pe(U),className:"text-muted-foreground hover:text-foreground transition-colors p-1",children:o.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-4 h-4",children:[o.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),o.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),o.jsx("button",{title:"Re-compose with AI",onClick:()=>Be(U),className:"text-muted-foreground hover:text-primary transition-colors p-1",children:o.jsx(Cs,{className:"w-4 h-4"})}),o.jsx("button",{className:"text-muted-foreground hover:text-foreground transition-colors p-1",onClick:()=>E(_===U.metadata.id?null:U.metadata.id),children:_===U.metadata.id?o.jsx(lu,{className:"w-4 h-4"}):o.jsx(Bo,{className:"w-4 h-4"})}),o.jsx("button",{onClick:()=>de(U.metadata.id),className:"text-muted-foreground hover:text-destructive transition-colors p-1",children:o.jsx(el,{className:"w-4 h-4"})})]})})]}),_===U.metadata.id&&o.jsxs("div",{className:"border-t px-5 py-4 bg-muted/20 space-y-3 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3 text-xs",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"font-bold uppercase tracking-widest text-[9px] text-muted-foreground mb-1",children:["Match (",U.spec.match.strategy,")"]}),U.spec.match.conditions.map((re,De)=>o.jsxs("div",{className:"text-muted-foreground",children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:re.type})," ",Array.isArray(re.value)?re.value.join(", "):re.value]},De))]}),o.jsxs("div",{children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] text-muted-foreground mb-1",children:"Extract"}),U.spec.extract?.map(re=>o.jsxs("div",{className:"text-muted-foreground",children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:re.key})," ","(",re.type,")",re.required?" *":""]},re.key))??o.jsx("span",{className:"text-muted-foreground/60",children:"—"})]}),o.jsxs("div",{children:[o.jsx("div",{className:"font-bold uppercase tracking-widest text-[9px] text-muted-foreground mb-1",children:"Actions"}),U.spec.actions?.map((re,De)=>o.jsxs("div",{className:"text-muted-foreground",children:[o.jsx("span",{className:"font-mono bg-muted px-1 rounded text-[10px]",children:re.type})," ",Ut(re)]},De))??o.jsx("span",{className:"text-muted-foreground/60",children:"—"})]})]}),(U.metadata.learning_examples??0)>0&&o.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Learned examples: ",U.metadata.learning_examples,U.metadata.learning_last_at?` · last on ${new Date(U.metadata.learning_last_at).toLocaleDateString()}`:""]})]})]},U.metadata.id))})]})]}),C==="packs"&&o.jsxs("div",{className:"space-y-4",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"Import curated policy bundles to instantly configure Folio for common use cases."}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:R6.map(U=>o.jsxs("div",{className:"rounded-2xl border bg-card/60 p-5 space-y-3 hover:border-primary/30 hover:shadow-md transition-all group",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"font-black text-sm",children:U.name}),o.jsxs(Mt,{variant:"outline",className:"text-[9px] shrink-0",children:[U.policies," policies"]})]}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:U.description})]}),o.jsx("div",{className:"flex flex-wrap gap-1",children:U.tags.map(re=>o.jsxs(Mt,{variant:"secondary",className:"text-[9px] gap-1",children:[o.jsx(du,{className:"w-2.5 h-2.5"}),re]},re))}),o.jsxs(ae,{size:"sm",variant:"outline",className:"w-full h-8 rounded-xl font-black text-[10px] uppercase tracking-widest group-hover:border-primary/40 transition-all",onClick:()=>ue.info(`"${U.name}" import coming soon!`),children:[o.jsx(RC,{className:"w-3 h-3 mr-2"}),"Import Pack"]})]},U.id))})]})]})}function Wa(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Wb(t){const e=[];for(const s of t){const i=Wa(s);if(!i)continue;const l=Wa(i.metadata)??{},u=Wa(i.spec)??{},d=Array.isArray(u.actions)?u.actions:[],h=typeof l.id=="string"?l.id.trim():"";if(!h)continue;const m=d.map(p=>{const y=Wa(p);return typeof y?.type=="string"?y.type.trim():""}).filter(p=>p==="append_to_google_sheet"||p==="webhook"||p==="copy_to_gdrive"||p==="copy"||p==="log_csv"||p==="notify");e.push({id:h,name:typeof l.name=="string"?l.name:h,priority:typeof l.priority=="number"?l.priority:100,riskyActions:m,learningExamples:typeof l.learning_examples=="number"?l.learning_examples:0,learningLastAt:typeof l.learning_last_at=="string"?l.learning_last_at:null})}return e.sort((s,i)=>i.priority-s.priority),e}function M6(t){if(!Array.isArray(t)||t.length===0)return null;const s=[...t].reverse().find(h=>{const m=String(h?.step??"").toLowerCase();return m.includes("learned fallback")||m.includes("learned policy candidate selected")});if(!s)return null;const i=String(s.step??"").toLowerCase(),l=Wa(s.details);if(!l)return null;const u=typeof l.reason=="string"?l.reason:i.includes("candidate selected")?"accepted":void 0,d=Wa(l.bestCandidate)??(typeof l.policyId=="string"||typeof l.score=="number"||typeof l.support=="number"?{policyId:l.policyId,score:l.score,support:l.support}:void 0);return{reason:u,evaluatedPolicies:typeof l.evaluatedPolicies=="number"?l.evaluatedPolicies:void 0,evaluatedSamples:typeof l.evaluatedSamples=="number"?l.evaluatedSamples:void 0,bestCandidate:d,topCandidates:Array.isArray(l.topCandidates)?l.topCandidates.map(h=>Wa(h)).filter(h=>!!h):void 0}}function D6(t){if(!t)return"No learned candidate details available yet.";switch(t){case"accepted":return"Learned fallback selected a policy candidate.";case"no_policy_ids":return"No candidate policies available for learned fallback.";case"no_document_features":return"Document had insufficient signals for learned fallback scoring.";case"no_feedback_samples":return"No learned examples yet. Match at least one document with learning enabled.";case"no_valid_samples":return"Learned examples exist but were too sparse to score.";case"score_below_threshold":return"A candidate was found but confidence stayed below threshold.";case"read_error":return"Learned fallback could not read feedback history.";default:return t.replace(/_/g," ")}}function P6({status:t}){return{pending:o.jsx(Qo,{className:"w-4 h-4 text-muted-foreground"}),processing:o.jsx(rt,{className:"w-4 h-4 text-blue-500 animate-spin"}),matched:o.jsx(os,{className:"w-4 h-4 text-emerald-500"}),no_match:o.jsx(em,{className:"w-4 h-4 text-amber-500"}),duplicate:o.jsx(em,{className:"w-4 h-4 text-emerald-500"}),error:o.jsx(Lw,{className:"w-4 h-4 text-destructive"})}[t]??null}function ra({children:t}){return o.jsx("div",{className:"text-[9px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5",children:t})}function z6(t){const e=[];t.status==="no_match"?e.push(`I have a document named "${t.filename}" that wasn't matched by any policy.`):e.push(`I have a document named "${t.filename}" that matched a policy, but I want to create a better, more specific policy for it.`),t.mime_type&&e.push(`It is a ${t.mime_type} file.`);const s=t.extracted?Object.entries(t.extracted).filter(([i,l])=>i!=="_enrichment"&&l!=null):[];if(s.length>0){const i=s.map(([l,u])=>`${l}: ${String(u)}`).join(", ");e.push(`Partial data already extracted: ${i}.`)}return e.push("Create a policy to handle this exact type of document — infer the document type, define strict match conditions, extract key fields, and route it to an appropriate folder."),e.join(" ")}function Jb(t){if(t==null)return"null";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t)}catch{return String(t)}}const L6=["issuer","vendor","sender","document_type","date","due_date","amount","total","currency"];function U6({extracted:t}){const e=L6.filter(s=>t[s]!=null&&String(t[s]).trim()!=="").map(s=>({key:s,value:String(t[s])}));return e.length===0?null:o.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.map(({key:s,value:i})=>o.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-muted border",children:[o.jsx("span",{className:"text-muted-foreground font-mono",children:s}),o.jsx("span",{className:"font-medium",children:i})]},s))})}function B6({tags:t,onChange:e}){const[s,i]=v.useState(""),l=v.useRef(null),u=m=>e(t.filter(p=>p!==m)),d=()=>{const m=s.toLowerCase().trim().replace(/\s+/g,"-");if(!m||t.includes(m)){i("");return}e([...t,m]),i("")},h=m=>{m.key==="Enter"||m.key===","?(m.preventDefault(),d()):m.key==="Backspace"&&!s&&t.length>0&&e(t.slice(0,-1))};return o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 rounded-xl border px-3 py-2 bg-background min-h-[36px] cursor-text",role:"button",tabIndex:0,onClick:()=>l.current?.focus(),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),l.current?.focus())},children:[t.map(m=>o.jsxs("span",{className:ve("inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full border",kp(m)),children:[m,o.jsx("button",{onClick:p=>{p.stopPropagation(),u(m)},className:"ml-0.5 opacity-60 hover:opacity-100 transition-opacity","aria-label":`Remove ${m}`,children:o.jsx(zn,{className:"w-2.5 h-2.5"})})]},m)),o.jsx("input",{ref:l,value:s,onChange:m=>i(m.target.value),onKeyDown:h,onBlur:d,placeholder:t.length?"":"Add tags…",className:"flex-1 min-w-[80px] bg-transparent text-xs outline-none placeholder:text-muted-foreground/50"}),s&&o.jsx("button",{onClick:d,className:"text-muted-foreground hover:text-foreground transition-colors",children:o.jsx(Ja,{className:"w-3 h-3"})})]})}function V6({ingestion:t,onClose:e,onRerun:s,onTagsChange:i,onComposePolicy:l,onManualMatch:u}){const d=t.extracted&&Object.keys(t.extracted).length>0?t.extracted:null,h=d&&typeof d._enrichment=="object"&&d._enrichment!==null?d._enrichment:null,m=t.actions_taken?.length?t.actions_taken:null,[p,y]=v.useState(t.summary??null),[x,w]=v.useState(!1),[j,T]=v.useState([]),[S,_]=v.useState(!1),[E,C]=v.useState(""),[A,k]=v.useState(!0),[M,P]=v.useState(!0),[B,R]=v.useState(!1),[I,te]=v.useState(!1),[ie,fe]=v.useState(null),[Ne,ye]=v.useState(!1),[se,V]=v.useState(!1),[F,J]=v.useState(null),[ge,ne]=v.useState([]),[D,L]=v.useState(null),[W,ee]=v.useState(!1),le=t.status!=="pending"&&t.status!=="processing",de=!!u&&!t.policy_name&&t.status!=="pending"&&t.status!=="processing",q=M6(t.trace);v.useEffect(()=>{if(!le||p)return;let ce=!1;return(async()=>{w(!0);try{const he=(await un()?.auth.getSession())?.data?.session?.access_token??null,Me=await Ee.summarizeIngestion(t.id,he);if(ce)return;Me.data?.summary&&y(Me.data.summary)}catch{}finally{ce||w(!1)}})(),()=>{ce=!0}},[t.id]),v.useEffect(()=>{if(!de)return;let ce=!1;return(async()=>{_(!0),fe(null);try{const he=(await un()?.auth.getSession())?.data?.session?.access_token??null,Me=await Ee.getPolicies(he);if(ce)return;if(Me?.error){const Ut=typeof Me.error=="string"?Me.error:Me.error.message;throw new Error(Ut||"Failed to load policies.")}const at=Wb(Me?.data?.policies??[]);T(at),C(Ut=>Ut||at[0]?.id||"")}catch{ce||(T([]),fe("Failed to load policies."))}finally{ce||_(!1)}})(),()=>{ce=!0}},[de,t.id]);const pe=v.useCallback(async()=>{if(!u||!E||I)return;const Fe=j.find(he=>he.id===E)?.riskyActions??[];if(M&&Fe.length>0&&!B){fe(`Re-run may trigger side-effect actions: ${Fe.join(", ")}. Enable side-effect confirmation to continue.`);return}te(!0),fe(null);try{await u({policyId:E,learn:A,rerun:M,allowSideEffects:M?B:!1}),J(null),ne([]),L(null)}catch(he){const Me=he instanceof Error?he.message:String(he);fe(Me||"Failed to assign policy.")}finally{te(!1)}},[B,I,A,u,j,M,E]),oe=v.useCallback(async()=>{if(!(!E||Ne||se)){ye(!0),L(null),J(null),ne([]);try{const Fe=(await un()?.auth.getSession())?.data?.session?.access_token??null,he=await Ee.suggestPolicyRefinement(t.id,{policyId:E},Fe);if(he?.error){const Ut=typeof he.error=="string"?he.error:he.error.message;throw new Error(Ut||"Unable to suggest refinement.")}const Me=he?.data?.suggestion?.policy;if(!Me)throw new Error("No policy refinement draft was returned.");const at=Array.isArray(he?.data?.suggestion?.rationale)?he.data.suggestion.rationale.map(Ut=>String(Ut).trim()).filter(Boolean):[];J(Me),ne(at),ee(!1)}catch(ce){const Fe=ce instanceof Error?ce.message:String(ce);L(Fe||"Unable to suggest refinement.")}finally{ye(!1)}}},[t.id,se,Ne,E]),ze=v.useCallback(async()=>{if(!(!F||se)){V(!0),L(null);try{const Fe=(await un()?.auth.getSession())?.data?.session?.access_token??null,he=await Ee.savePolicy(F,Fe);if(he?.error){const at=typeof he.error=="string"?he.error:he.error.message;throw new Error(at||"Failed to apply refinement.")}ue.success(`Applied refinement to policy "${F.metadata.name}".`),J(null),ne([]),L(null),ee(!1);const Me=await Ee.getPolicies(Fe);if(!Me?.error){const at=Wb(Me?.data?.policies??[]);T(at)}}catch(ce){const Fe=ce instanceof Error?ce.message:String(ce);L(Fe||"Failed to apply refinement.")}finally{V(!1)}}},[se,F]),Be=j.find(ce=>ce.id===E),kt=Be?.riskyActions??[],et=v.useCallback(ce=>{ce.target===ce.currentTarget&&e()},[e]);return o.jsx("div",{className:"fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4",role:"button",tabIndex:0,onClick:et,onKeyDown:ce=>{ce.key==="Escape"&&(ce.preventDefault(),e()),(ce.key==="Enter"||ce.key===" ")&&ce.target===ce.currentTarget&&(ce.preventDefault(),e())},children:o.jsxs("div",{className:"bg-background border rounded-2xl shadow-2xl w-full max-w-3xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-200",children:[o.jsxs("div",{className:"flex items-start gap-3 px-6 pt-5 pb-4 border-b",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-muted flex items-center justify-center shrink-0 mt-0.5",children:o.jsx(Vm,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h2",{className:"font-bold text-sm truncate",title:t.filename,children:t.filename}),o.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[t.source," · ",new Date(t.created_at).toLocaleString(),t.file_size&&` · ${(t.file_size/1024).toFixed(1)}KB`]})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx(P6,{status:t.status}),o.jsx("button",{onClick:e,className:"text-muted-foreground hover:text-foreground transition-colors",children:o.jsx(zn,{className:"w-4 h-4"})})]})]}),o.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto max-h-[65vh]",children:[le&&o.jsxs("div",{children:[o.jsx(ra,{children:o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx(Cs,{className:"w-2.5 h-2.5"}),"Summary"]})}),d&&o.jsx("div",{className:"mb-2",children:o.jsx(U6,{extracted:d})}),x?o.jsxs("div",{className:"space-y-2",children:[o.jsx("div",{className:"h-3 rounded bg-muted animate-pulse w-full"}),o.jsx("div",{className:"h-3 rounded bg-muted animate-pulse w-5/6"}),o.jsx("div",{className:"h-3 rounded bg-muted animate-pulse w-4/6"})]}):p?o.jsx("p",{className:"text-xs text-foreground/80 leading-relaxed",children:p}):o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No summary available."})]}),!le&&o.jsx("div",{className:"rounded-xl bg-muted/40 border px-4 py-3 text-xs text-muted-foreground text-center",children:"Summary will be available after processing completes."}),o.jsxs("div",{children:[o.jsx(ra,{children:o.jsxs("span",{className:"inline-flex items-center gap-1",children:[o.jsx(du,{className:"w-2.5 h-2.5"}),"Tags"]})}),o.jsx(B6,{tags:t.tags??[],onChange:i}),o.jsx("p",{className:"text-[10px] text-muted-foreground mt-1.5",children:"Enter to add · Backspace to remove · spaces become hyphens"})]}),o.jsxs("div",{children:[o.jsx(ra,{children:"Policy Matched"}),t.policy_name?o.jsx(Mt,{variant:"secondary",children:t.policy_name}):o.jsxs("div",{className:"space-y-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"No policy matched"}),de&&o.jsxs("div",{className:"rounded-xl border bg-muted/20 p-3 space-y-2",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-wider font-semibold text-muted-foreground",children:"Assign To Existing Policy"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("select",{className:"flex-1 h-8 rounded-lg border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-primary/30",value:E,onChange:ce=>{C(ce.target.value),R(!1),fe(null),J(null),ne([]),L(null)},disabled:S||I||j.length===0,children:j.length===0?o.jsx("option",{value:"",children:S?"Loading policies…":"No active policies"}):j.map(ce=>o.jsx("option",{value:ce.id,children:ce.learningExamples>0?`${ce.name} (${ce.learningExamples} learned)`:ce.name},ce.id))}),o.jsx(ae,{variant:"outline",size:"sm",className:"h-8 rounded-lg",disabled:I||S||!E,onClick:pe,children:I?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):"Match To Policy"}),o.jsx(ae,{variant:"outline",size:"sm",className:"h-8 rounded-lg",disabled:Ne||se||S||!E,onClick:oe,children:Ne?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):"Suggest Refinement"})]}),Be&&o.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Learned examples for this policy: ",Be.learningExamples,Be.learningLastAt?` · last on ${new Date(Be.learningLastAt).toLocaleDateString()}`:""]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[o.jsx("input",{type:"checkbox",className:"rounded border-muted-foreground/40",checked:A,onChange:ce=>k(ce.target.checked),disabled:I}),"Learn from this match"]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[o.jsx("input",{type:"checkbox",className:"rounded border-muted-foreground/40",checked:M,onChange:ce=>{P(ce.target.checked),R(!1),fe(null)},disabled:I}),"Re-run ingestion now (recommended)"]}),M&&kt.length>0&&o.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 p-2 text-[11px] text-amber-700 space-y-1",children:[o.jsxs("p",{children:["This policy has side-effect actions: ",kt.join(", ")]}),o.jsxs("label",{className:"inline-flex items-center gap-1.5 text-[11px]",children:[o.jsx("input",{type:"checkbox",className:"rounded border-amber-500/40",checked:B,onChange:ce=>R(ce.target.checked),disabled:I}),"I understand this may create external writes on re-run"]})]}),(F||D)&&o.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-2.5 space-y-2",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-wider font-semibold text-primary",children:"Policy Refinement Preview"}),D&&o.jsx("p",{className:"text-[11px] text-destructive",children:D}),F&&o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"text-[11px] text-foreground/90",children:[F.metadata.name," · ",F.spec.match.conditions.length," match conditions · ",(F.spec.extract??[]).length," extract fields"]}),ge.length>0&&o.jsx("div",{className:"space-y-1",children:ge.map((ce,Fe)=>o.jsx("p",{className:"text-[10px] text-muted-foreground",children:ce},`refine-rationale-${Fe}`))}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx(ae,{variant:"outline",size:"sm",className:"h-7 rounded-lg text-[10px]",onClick:()=>ee(ce=>!ce),children:W?"Hide JSON":"Show JSON"}),o.jsx(ae,{size:"sm",className:"h-7 rounded-lg text-[10px]",onClick:ze,disabled:se,children:se?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):"Apply To Policy"}),o.jsx(ae,{variant:"ghost",size:"sm",className:"h-7 rounded-lg text-[10px]",onClick:()=>{J(null),ne([]),L(null),ee(!1)},children:"Discard"})]}),W&&o.jsx("pre",{className:"rounded-md border border-border/40 bg-background p-2 text-[10px] overflow-auto max-h-48 whitespace-pre-wrap font-mono",children:JSON.stringify(F,null,2)})]})]}),ie&&o.jsx("p",{className:"text-[11px] text-destructive",children:ie})]})]})]}),q&&o.jsxs("div",{children:[o.jsx(ra,{children:"Learning Diagnostics"}),o.jsxs("div",{className:"rounded-xl border bg-muted/20 px-4 py-3 space-y-1.5",children:[o.jsx("p",{className:"text-xs text-foreground/90",children:D6(q.reason)}),(q.evaluatedPolicies!==void 0||q.evaluatedSamples!==void 0)&&o.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Evaluated policies: ",q.evaluatedPolicies??0," · samples: ",q.evaluatedSamples??0]}),q.bestCandidate&&o.jsxs("p",{className:"text-[11px] text-muted-foreground font-mono",children:["Best: ",String(q.bestCandidate.policyId??"-")," · score ",String(q.bestCandidate.score??"-")," · support ",String(q.bestCandidate.support??"-"),q.bestCandidate.requiredScore!==void 0?` · needed ${String(q.bestCandidate.requiredScore)}`:""]})]})]}),d&&o.jsxs("div",{children:[o.jsx(ra,{children:"Extracted Data"}),o.jsx("div",{className:"rounded-xl border overflow-hidden",children:Object.entries(d).filter(([ce])=>ce!=="_enrichment").map(([ce,Fe])=>o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 text-xs border-b last:border-0",children:[o.jsx("span",{className:"font-mono text-muted-foreground",children:ce}),o.jsx("span",{className:"font-medium text-right max-w-[55%] truncate",children:Jb(Fe)})]},ce))})]}),h&&Object.keys(h).length>0&&o.jsxs("div",{children:[o.jsx(ra,{children:"Enrichment Data"}),o.jsx("div",{className:"rounded-xl border overflow-hidden",children:Object.entries(h).map(([ce,Fe])=>o.jsxs("div",{className:"px-4 py-2 text-xs border-b last:border-0",children:[o.jsx("div",{className:"font-mono text-muted-foreground mb-1",children:ce}),o.jsx("pre",{className:"font-medium whitespace-pre-wrap break-all",children:Jb(Fe)})]},ce))})]}),m&&o.jsxs("div",{children:[o.jsx(ra,{children:"Actions Taken"}),o.jsx("ul",{className:"space-y-1",children:m.map((ce,Fe)=>o.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[o.jsx(os,{className:"w-3 h-3 text-emerald-500 shrink-0"}),o.jsx("span",{className:"text-muted-foreground",children:String(ce)})]},Fe))})]}),t.error_message&&o.jsxs("div",{children:[o.jsx(ra,{children:"Error"}),o.jsx("div",{className:"rounded-xl bg-destructive/5 border border-destructive/20 px-4 py-3",children:o.jsx("p",{className:"text-xs text-destructive font-mono break-all",children:t.error_message})})]}),!d&&!m&&!t.error_message&&le&&!x&&!p&&o.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No extracted data or actions recorded."})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t bg-muted/20",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ae,{variant:"outline",size:"sm",onClick:s,className:"gap-2 rounded-xl",children:[o.jsx(ma,{className:"w-3.5 h-3.5"}),"Re-run"]}),l&&o.jsxs(ae,{variant:"outline",size:"sm",onClick:()=>l(z6(t)),className:"gap-2 rounded-xl border-primary/30 text-primary hover:bg-primary/5 hover:text-primary",children:[o.jsx(Cs,{className:"w-3.5 h-3.5"}),"Create Policy"]})]}),o.jsx(ae,{variant:"ghost",size:"sm",onClick:e,className:"rounded-xl",children:"Close"})]})]})})}function I6({children:t}){return o.jsx("h3",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3",children:t})}function $6({ingestion:t,onClose:e}){return o.jsx("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200",children:o.jsxs("div",{className:"bg-card w-full max-w-3xl rounded-2xl shadow-xl border overflow-hidden flex flex-col max-h-[90vh]",children:[o.jsxs("div",{className:"px-6 py-4 border-b flex items-center justify-between bg-muted/20",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-500/10 flex items-center justify-center",children:o.jsx(Io,{className:"w-4 h-4 text-emerald-500"})}),o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold",children:"AI Processing Trace"}),o.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[400px]",title:t.filename,children:t.filename})]})]}),o.jsx("button",{onClick:e,className:"p-2 -mr-2 text-muted-foreground hover:text-foreground hover:bg-muted rounded-xl transition-colors",children:o.jsx(zn,{className:"w-4 h-4"})})]}),o.jsx("div",{className:"p-6 overflow-y-auto space-y-6",children:t.trace&&t.trace.length>0?o.jsxs("div",{children:[o.jsx(I6,{children:"Execution Log"}),o.jsx("div",{className:"rounded-xl bg-zinc-950 text-emerald-400 p-4 font-mono text-[11px] space-y-3 overflow-x-auto border border-zinc-800 shadow-inner max-h-[60vh] overflow-y-auto",children:[...t.trace].reverse().map((s,i)=>o.jsxs("div",{className:`flex gap-3 leading-relaxed ${s.step.startsWith("---")?"text-zinc-500 my-4 text-center justify-center":""}`,children:[!s.step.startsWith("---")&&o.jsx("span",{className:"opacity-40 shrink-0",children:new Date(s.timestamp).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}),o.jsxs("div",{className:s.step.startsWith("---")?"font-bold uppercase tracking-widest":"",children:[o.jsx("span",{className:"font-semibold text-zinc-100",children:s.step}),s.details&&Object.keys(s.details).length>0&&o.jsxs("pre",{className:"mt-1 flex text-emerald-500/80 whitespace-pre-wrap text-[10px]",children:[o.jsx("span",{className:"select-none opacity-30 mr-2",children:"↳"}),JSON.stringify(s.details,null,2)]})]})]},i))})]}):o.jsx("p",{className:"text-sm text-muted-foreground text-center py-12 border-2 border-dashed rounded-xl",children:"No trace logs available for this ingestion."})})]})})}const Qb=["bg-blue-500/10 text-blue-600 border-blue-500/20","bg-emerald-500/10 text-emerald-600 border-emerald-500/20","bg-amber-500/10 text-amber-700 border-amber-500/20","bg-violet-500/10 text-violet-600 border-violet-500/20","bg-rose-500/10 text-rose-600 border-rose-500/20","bg-cyan-500/10 text-cyan-600 border-cyan-500/20","bg-orange-500/10 text-orange-600 border-orange-500/20"];function kp(t){let e=0;for(const s of t)e=e*31+s.charCodeAt(0)>>>0;return Qb[e%Qb.length]}function q6({status:t}){const e={pending:{label:"Pending",icon:o.jsx(Qo,{className:"w-3 h-3"}),cls:"bg-muted text-muted-foreground"},processing:{label:"Processing",icon:o.jsx(rt,{className:"w-3 h-3 animate-spin"}),cls:"bg-blue-500/10 text-blue-500"},matched:{label:"Matched",icon:o.jsx(os,{className:"w-3 h-3"}),cls:"bg-emerald-500/10 text-emerald-500"},no_match:{label:"No Match",icon:o.jsx(em,{className:"w-3 h-3"}),cls:"bg-amber-500/10 text-amber-600"},error:{label:"Error",icon:o.jsx(Lw,{className:"w-3 h-3"}),cls:"bg-destructive/10 text-destructive"},duplicate:{label:"Duplicate",icon:o.jsx(Qk,{className:"w-3 h-3"}),cls:"bg-violet-500/10 text-violet-500"}},s=e[t]??e.pending;return o.jsxs("span",{className:ve("inline-flex items-center gap-1 text-[10px] font-medium px-2 py-0.5 rounded-full",s.cls),children:[s.icon,s.label]})}function H6({source:t}){const e={upload:"📄",dropzone:"📂",email:"📧",url:"🔗"};return o.jsxs("span",{className:"text-xs text-muted-foreground",children:[e[t]??"📄"," ",t]})}function G6(t){return t?t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`:""}function F6({tags:t,activeFilters:e,onToggle:s}){if(!t.length)return null;const i=t.slice(0,3),l=t.length-i.length;return o.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[i.map(u=>o.jsx("button",{onClick:d=>s(u,d),className:ve("inline-flex items-center text-[9px] px-1.5 py-0 rounded-full border transition-all",kp(u),e.has(u)&&"ring-1 ring-current font-semibold"),children:u},u)),l>0&&o.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["+",l]})]})}function K6({allTags:t,activeFilters:e,onToggle:s,onClear:i}){return t.length?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground shrink-0",children:[o.jsx(du,{className:"w-3 h-3"}),o.jsx("span",{children:"Filter by tag:"})]}),o.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:t.map(l=>o.jsx("button",{onClick:()=>s(l),className:ve("inline-flex items-center text-[10px] px-2 py-0.5 rounded-full border transition-all",kp(l),e.has(l)?"ring-1 ring-current font-semibold shadow-sm":"opacity-70 hover:opacity-100"),children:l},l))}),e.size>0&&o.jsxs("button",{onClick:i,className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors",children:[o.jsx(zn,{className:"w-3 h-3"}),"Clear"]})]}):null}const Vf=20;function Y6({page:t,total:e,pageSize:s,onPage:i}){const l=Math.max(1,Math.ceil(e/s));if(l<=1&&e<=s)return null;const u=e===0?0:(t-1)*s+1,d=Math.min(t*s,e);return o.jsxs("div",{className:"flex items-center justify-between px-1 pt-2",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:e===0?"No results":`${u}–${d} of ${e}`}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ae,{variant:"outline",size:"sm",className:"h-7 px-2 rounded-lg",onClick:()=>i(t-1),disabled:t<=1,children:o.jsx(Jo,{className:"w-3.5 h-3.5"})}),o.jsxs("span",{className:"text-xs text-muted-foreground px-2",children:["Page ",t," of ",l]}),o.jsx(ae,{variant:"outline",size:"sm",className:"h-7 px-2 rounded-lg",onClick:()=>i(t+1),disabled:t>=l,children:o.jsx(hr,{className:"w-3.5 h-3.5"})})]})]})}function X6({onComposePolicyForDoc:t}){const[e,s]=v.useState([]),[i,l]=v.useState(0),[u,d]=v.useState(1),[h,m]=v.useState(!0),[p,y]=v.useState(!1),[x,w]=v.useState(!1),[j,T]=v.useState(null),[S,_]=v.useState(null),[E,C]=v.useState(null),[A,k]=v.useState(new Set),[M,P]=v.useState([]),[B,R]=v.useState(""),[I,te]=v.useState(""),ie=v.useRef(null),fe=v.useRef(null),Ne=L=>{R(L),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{te(L),d(1)},300)},ye=v.useCallback(async(L=u)=>{if(j===null)return;m(!0);const W=await Ee.getIngestions({page:L,pageSize:Vf,q:I||void 0},j),ee=W?.data?.ingestions??[];s(ee),l(W?.data?.total??0),m(!1),P(le=>[...new Set([...le,...ee.flatMap(q=>q.tags??[])])].sort())},[j,I,u]);v.useEffect(()=>{const L=un();L&&L.auth.getSession().then(({data:W})=>{T(W.session?.access_token??null)})},[]),v.useEffect(()=>{j!==null&&ye(u)},[j,I,u]);const se=v.useMemo(()=>A.size?e.filter(L=>[...A].every(W=>L.tags?.includes(W))):e,[e,A]),V=L=>{k(W=>{const ee=new Set(W);return ee.has(L)?ee.delete(L):ee.add(L),ee}),d(1)},F=async L=>{const W=Array.from(L);if(W.length){w(!0);try{for(const ee of W){ue.info(`Ingesting ${ee.name}…`);const le=await Ee.uploadDocument?.(ee,j);if(le?.success)if(le.ingestion?.status==="duplicate"){const de=le.ingestion.extracted?.original_filename??"a previous upload";ue.warning(`${ee.name} is a duplicate of "${de}" — skipped.`)}else ue.success(`${ee.name} → ${le.ingestion?.status}`);else ue.error(`Failed to ingest ${ee.name}`)}d(1),await ye(1)}finally{w(!1)}}},J=L=>{L.preventDefault(),y(!1),F(L.dataTransfer.files)},ge=async(L,W)=>{W.stopPropagation(),await Ee.rerunIngestion?.(L,j),ue.success("Re-running…"),await ye(u)},ne=async(L,W)=>{if(W.stopPropagation(),!window.confirm("Delete this ingestion record?"))return;await Ee.deleteIngestion?.(L,j),ue.success("Deleted.");const ee=i-1,le=Math.max(1,Math.ceil(ee/Vf)),de=Math.min(u,le);d(de),await ye(de)},D=async(L,W)=>{s(ee=>ee.map(le=>le.id===L?{...le,tags:W}:le)),S?.id===L&&_(ee=>ee&&{...ee,tags:W}),await Ee.updateIngestionTags(L,W,j),P(ee=>[...new Set([...ee,...W])].sort())};return o.jsxs("div",{className:"w-full mx-auto px-8 py-10 space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:o.jsx(Bw,{className:"w-5 h-5 text-primary"})}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-xl font-bold",children:"Funnel"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Document ingestion pipeline"})]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsxs(ae,{variant:"outline",size:"sm",onClick:()=>ye(u),className:"gap-2 rounded-xl",children:[o.jsx(ma,{className:"w-3.5 h-3.5"}),"Refresh"]}),o.jsxs(ae,{size:"sm",onClick:()=>fe.current?.click(),disabled:x,className:"gap-2 rounded-xl",children:[x?o.jsx(rt,{className:"w-3.5 h-3.5 animate-spin"}):o.jsx(tm,{className:"w-3.5 h-3.5"}),"Upload"]}),o.jsx("input",{ref:fe,type:"file",multiple:!0,hidden:!0,onChange:L=>L.target.files&&F(L.target.files)})]})]}),o.jsxs("div",{onDragOver:L=>{L.preventDefault(),y(!0)},onDragLeave:()=>y(!1),onDrop:J,onClick:()=>fe.current?.click(),className:ve("rounded-2xl border-2 border-dashed transition-all cursor-pointer flex flex-col items-center justify-center gap-2 py-8",p?"border-primary bg-primary/5 scale-[1.01]":"border-muted-foreground/20 hover:border-primary/50 hover:bg-muted/30"),children:[o.jsx(tm,{className:ve("w-8 h-8 transition-colors",p?"text-primary":"text-muted-foreground/50")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:p?"Drop to ingest":"Drag & drop files here, or click to browse"}),o.jsx("p",{className:"text-xs text-muted-foreground/60",children:".txt, .md, .pdf, .docx — up to 20MB"})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"relative",children:[o.jsx(qC,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),o.jsx("input",{type:"text",value:B,onChange:L=>Ne(L.target.value),placeholder:"Search filename, policy, summary…",className:"w-full pl-9 pr-9 py-2 text-sm rounded-xl border bg-background placeholder:text-muted-foreground/50 outline-none focus:ring-2 focus:ring-primary/30 transition"}),B&&o.jsx("button",{onClick:()=>{R(""),te(""),d(1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors",children:o.jsx(zn,{className:"w-3.5 h-3.5"})})]}),M.length>0&&o.jsx(K6,{allTags:M,activeFilters:A,onToggle:V,onClear:()=>k(new Set)})]}),o.jsx("div",{className:"rounded-2xl border overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"bg-muted/40 border-b",children:o.jsxs("tr",{children:[o.jsx("th",{className:"text-left px-5 py-3 text-xs font-semibold text-muted-foreground",children:"File"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Status"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Policy"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Source"}),o.jsx("th",{className:"text-left px-4 py-3 text-xs font-semibold text-muted-foreground",children:"Date"}),o.jsx("th",{className:"px-4 py-3"})]})}),o.jsx("tbody",{className:"divide-y",children:h?o.jsx("tr",{children:o.jsxs("td",{colSpan:6,className:"text-center py-12 text-muted-foreground",children:[o.jsx(rt,{className:"w-5 h-5 animate-spin mx-auto mb-2"}),"Loading…"]})}):se.length===0?o.jsx("tr",{children:o.jsxs("td",{colSpan:6,className:"text-center py-16 text-muted-foreground",children:[o.jsx(Vm,{className:"w-8 h-8 mx-auto mb-3 opacity-30"}),o.jsx("p",{className:"text-sm",children:I||A.size>0?"No documents match your search.":"No ingestions yet — upload a document above."}),(I||A.size>0)&&o.jsx("button",{className:"mt-2 text-xs text-primary hover:underline",onClick:()=>{R(""),te(""),k(new Set),d(1)},children:"Clear filters"})]})}):se.map(L=>o.jsxs("tr",{onClick:()=>_(L),className:ve("cursor-pointer transition-colors",L.status==="processing"?"animate-pulse bg-blue-500/5 hover:bg-blue-500/10":"hover:bg-muted/30"),children:[o.jsxs("td",{className:"px-5 py-3.5",children:[o.jsx("div",{className:"font-medium text-sm truncate max-w-[220px]",title:L.filename,children:L.filename}),L.status==="duplicate"?o.jsxs("div",{className:"text-xs text-violet-500/80 truncate max-w-[220px]",children:["↳ ",L.extracted?.original_filename??"previously processed"]}):L.file_size&&o.jsx("div",{className:"text-xs text-muted-foreground",children:G6(L.file_size)}),o.jsx(F6,{tags:L.tags??[],activeFilters:A,onToggle:(W,ee)=>{ee.stopPropagation(),V(W)}})]}),o.jsx("td",{className:"px-4 py-3.5",children:o.jsx(q6,{status:L.status})}),o.jsx("td",{className:"px-4 py-3.5",children:L.policy_name?o.jsx(Mt,{variant:"secondary",className:"text-[10px]",children:L.policy_name}):o.jsx("span",{className:"text-muted-foreground/50 text-xs",children:"—"})}),o.jsx("td",{className:"px-4 py-3.5",children:o.jsx(H6,{source:L.source})}),o.jsx("td",{className:"px-4 py-3.5 text-xs text-muted-foreground whitespace-nowrap",children:new Date(L.created_at).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"})}),o.jsx("td",{className:"px-4 py-3.5",children:o.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[o.jsx("button",{title:"View Processing Trace",onClick:W=>{W.stopPropagation(),C(L)},className:"text-muted-foreground hover:text-emerald-500 p-1 transition-colors",children:o.jsx(Io,{className:"w-3.5 h-3.5"})}),o.jsx("button",{title:"Re-run",onClick:W=>ge(L.id,W),className:"text-muted-foreground hover:text-foreground p-1 transition-colors",children:o.jsx(ma,{className:"w-3.5 h-3.5"})}),o.jsx("button",{title:"Delete",onClick:W=>ne(L.id,W),className:"text-muted-foreground hover:text-destructive p-1 transition-colors",children:o.jsx(el,{className:"w-3.5 h-3.5"})}),o.jsx(hr,{className:"w-3.5 h-3.5 text-muted-foreground/40"})]})})]},L.id))})]})}),o.jsx(Y6,{page:u,total:i,pageSize:Vf,onPage:L=>d(L)}),S&&o.jsx(V6,{ingestion:S,onClose:()=>_(null),onTagsChange:L=>D(S.id,L),onRerun:async()=>{await Ee.rerunIngestion?.(S.id,j),await ye(u),_(null),ue.success("Re-running ingestion…")},onComposePolicy:t?L=>{_(null),t(L)}:void 0,onManualMatch:async({policyId:L,learn:W,rerun:ee,allowSideEffects:le})=>{const de=await Ee.matchIngestionToPolicy(S.id,{policyId:L,learn:W,rerun:ee,allowSideEffects:le},j);if(de?.error){const pe=typeof de.error=="string"?de.error:de.error.message;throw new Error(pe||"Failed to match ingestion to policy.")}const q=de?.data?.ingestion;if(!q)throw new Error("Match succeeded but updated ingestion payload is missing.");q&&(s(pe=>pe.map(oe=>oe.id===q.id?q:oe)),_(q)),await ye(u),ee?ue.success(W?"Policy matched, learned, and re-run started.":"Policy matched and re-run started."):ue.success(W?"Policy match saved and learned.":"Policy match saved.")}}),E&&o.jsx($6,{ingestion:E,onClose:()=>C(null)})]})}function W6({activeSessionId:t,onSelectSession:e,refreshTrigger:s}){const[i,l]=v.useState([]),[u,d]=v.useState(!0),h=v.useCallback(async()=>{const y=un();if(!y)return null;const{data:x}=await y.auth.getSession();return x.session?.access_token??null},[]),m=v.useCallback(async()=>{try{const y=await h(),x=await Ee.getChatSessions(y);x.data?.success&&l(x.data.sessions)}catch(y){console.error("Failed to fetch sessions",y)}finally{d(!1)}},[h]);v.useEffect(()=>{m()},[m,s]);const p=async(y,x)=>{y.stopPropagation();try{const w=await un();if(!w)return;const{error:j}=await w.from("chat_sessions").delete().eq("id",x);j||(l(T=>T.filter(S=>S.id!==x)),t===x&&e(null))}catch(w){console.error(w)}};return o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx("div",{className:"p-3 border-b border-border bg-surface/15",children:o.jsxs("button",{onClick:()=>e(null),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary/10 hover:bg-primary/20 text-primary rounded-xl transition-all font-semibold text-sm border border-primary/20 cursor-pointer",children:[o.jsx(Ja,{size:16}),"New Chat"]})}),o.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1 scrollbar-on-hover",children:u?o.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"Loading..."}):i.length===0?o.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[o.jsx(cu,{size:24,className:"mx-auto opacity-20 mb-2"}),o.jsx("p",{className:"text-xs",children:"No chat history"})]}):i.map(y=>o.jsxs("div",{onClick:()=>e(y.id),className:`group flex items-center justify-between px-3 py-3 rounded-lg cursor-pointer transition-all text-sm ${t===y.id?"bg-primary/15 text-foreground ring-1 ring-primary/30 font-medium":"text-muted-foreground hover:bg-surface/50 hover:text-foreground"}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5 overflow-hidden",children:[o.jsx(cu,{size:14,className:t===y.id?"text-primary":"opacity-50"}),o.jsx("span",{className:"truncate",children:y.title})]}),o.jsx("button",{onClick:x=>p(x,y.id),className:"opacity-0 group-hover:opacity-100 p-1.5 hover:bg-destructive/10 hover:text-destructive rounded transition-all",children:o.jsx(el,{size:12})})]},y.id))})]})}function J6({message:t}){const e=t.role==="user",s=i=>i.split(`
113
113
  `).map((l,u)=>o.jsxs("span",{children:[l,o.jsx("br",{})]},u));return o.jsx("div",{className:`flex w-full ${e?"justify-end":"justify-start"}`,children:o.jsxs("div",{className:`flex gap-3 max-w-[85%] ${e?"flex-row-reverse":"flex-row"}`,children:[o.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 shadow-sm ${e?"bg-primary text-primary-foreground":"bg-surface border border-border shadow-inner text-foreground"}`,children:e?o.jsx(ku,{size:14,strokeWidth:2.5}):o.jsx(Zf,{size:14,className:"text-primary",strokeWidth:2.5})}),o.jsxs("div",{className:`flex flex-col ${e?"items-end":"items-start"}`,children:[o.jsx("div",{className:`px-4 py-3 rounded-2xl text-[13px] leading-relaxed shadow-sm ${e?"bg-primary text-primary-foreground rounded-tr-sm":"bg-surface border border-border/60 text-foreground rounded-tl-sm"}`,children:o.jsx("div",{className:"font-sans break-words whitespace-pre-wrap",children:s(t.content)})}),o.jsxs("div",{className:"flex items-center gap-2 mt-1.5 px-1",children:[o.jsx("span",{className:"text-[10px] text-muted-foreground/50 font-medium tracking-wide",children:new Date(t.created_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}),!e&&t.context_sources&&t.context_sources.length>0&&o.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-secondary/20 text-secondary border border-secondary/20 flex items-center gap-1 font-medium",children:[o.jsx(Zf,{size:10}),t.context_sources.length," sources"]})]})]})]})})}function Fc(t){return typeof t=="string"?t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"?t.message:"Request failed"}function Q6({sessionId:t,onContextUpdate:e,onSessionCreated:s}){const[i,l]=v.useState([]),[u,d]=v.useState(""),[h,m]=v.useState(!1),[p,y]=v.useState(!1),[x,w]=v.useState(!1),j=v.useRef(null),T=v.useRef(null),S=v.useRef(!0),_=v.useRef(null),E=v.useRef(null),C=v.useRef(null),A=v.useCallback(async()=>{const I=un();if(!I)return null;const{data:te}=await I.auth.getSession();return te.session?.access_token??null},[]),k=v.useCallback(async I=>{try{const te=await A();if(!te)throw new Error("Authentication required");const ie=await Ee.getChatMessages(I,te);if(ie.error)throw new Error(Fc(ie.error));if(ie.data?.success&&E.current===I){l(ie.data.messages);const fe=ie.data.messages.filter(Ne=>Ne.role==="assistant"&&Array.isArray(Ne.context_sources)).flatMap(Ne=>Ne.context_sources??[]);e(fe)}}catch(te){console.error("Failed to fetch messages",te),ue.error("Failed to load chat history")}finally{E.current===I&&w(!1)}},[A,e]);v.useEffect(()=>{if(t){if(C.current===t){C.current=null,w(!1);return}l([]),w(!0),E.current=t,k(t)}else l([]),w(!1),e([]),E.current=null},[t,k,e]),v.useEffect(()=>{S.current&&j.current&&j.current.scrollIntoView({behavior:"smooth"})},[i,p]);const M=()=>{const I=T.current;if(!I)return;const te=I.scrollHeight-I.scrollTop-I.clientHeight;S.current=te<64},P=async I=>{if(I?.preventDefault(),!u.trim()||h)return;const te=u.trim();d(""),_.current&&(_.current.style.height="auto"),m(!0),y(!0);try{const ie=await A();if(!ie)throw new Error("Authentication required");const fe={id:"temp-"+Date.now(),role:"user",content:te,created_at:new Date().toISOString()};l(V=>[...V,fe]);let Ne=t;if(!Ne){const V=await Ee.createChatSession(ie);if(V.error)throw new Error(Fc(V.error));if(V.data?.success)Ne=V.data.session.id,C.current=Ne,s(Ne);else throw new Error("Failed to create session")}const ye=await Ee.sendChatMessage({sessionId:Ne,content:te},ie);if(ye.error)throw new Error(Fc(ye.error));const se=ye.data?.message;ye.data?.success&&se&&(l(V=>[...V,se]),se.context_sources&&se.context_sources.length>0&&e(se.context_sources))}catch(ie){console.error("Message failed",ie),ue.error(Fc(ie)||"Failed to send message"),l(fe=>[...fe,{id:"err-"+Date.now(),role:"assistant",content:"I encountered an error trying to process that request.",created_at:new Date().toISOString()}])}finally{m(!1),y(!1)}},B=I=>{I.key==="Enter"&&!I.shiftKey&&(I.preventDefault(),P())},R=["Find me the latest invoice from AWS.","What is the late penalty on the ACME contract?","Show me receipts from last week.","Summarize my recent cloud hosting expenses."];return o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:T,onScroll:M,className:"flex-1 overflow-y-auto p-5 space-y-6 scrollbar-on-hover",children:[x?o.jsxs("div",{className:"flex-1 h-full flex items-center justify-center text-muted-foreground gap-2",children:[o.jsx(ma,{size:18,className:"animate-spin"}),o.jsx("span",{className:"text-sm",children:"Loading history..."})]}):i.length===0?o.jsxs("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center text-muted-foreground/80",children:[o.jsx("div",{className:"w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center mb-6 text-primary",children:o.jsx(Cs,{size:32})}),o.jsx("h3",{className:"text-2xl font-bold mb-3 text-foreground tracking-tight",children:"Chat with your Documents"}),o.jsx("p",{className:"text-sm max-w-sm mx-auto mb-10 leading-relaxed",children:"Folio has seamlessly read and memorized your files using Semantic Search. Ask any question to retrieve precise answers and exact page citations."}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 max-w-lg w-full",children:R.map((I,te)=>o.jsx("button",{onClick:()=>d(I),className:"text-left p-3.5 text-xs font-medium bg-surface/30 hover:bg-surface border border-border/50 hover:border-border rounded-xl transition-all cursor-pointer shadow-sm hover:shadow",children:I},te))})]}):o.jsxs(o.Fragment,{children:[i.map(I=>o.jsx(J6,{message:I},I.id)),o.jsx(_p,{children:p&&o.jsx(Ro.div,{initial:{opacity:0,scale:.95,y:10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:10},className:"flex justify-start w-full",children:o.jsx("div",{className:"bg-surface border border-border/50 rounded-2xl rounded-tl-none px-4 py-3.5 flex items-center gap-3 shadow-sm",children:o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0s"}}),o.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.15s"}}),o.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.3s"}})]})})})})]}),o.jsx("div",{ref:j})]}),o.jsx("div",{className:"p-4 bg-surface/40 backdrop-blur-xl border-t border-border/50",children:o.jsx("form",{onSubmit:P,className:"relative max-w-4xl mx-auto",children:o.jsxs("div",{className:"relative flex items-end gap-2 bg-surface/80 border border-border/60 hover:border-border rounded-2xl px-3 py-2 shadow-sm transition-all focus-within:ring-2 focus-within:ring-primary/20 focus-within:border-primary/50",children:[o.jsx("textarea",{ref:_,value:u,onChange:I=>{d(I.target.value),I.target.style.height="auto",I.target.style.height=Math.min(I.target.scrollHeight,200)+"px"},onKeyDown:B,placeholder:"Message Folio AI...",rows:1,className:"w-full bg-transparent border-none focus:ring-0 focus:outline-none py-2.5 pl-1 text-sm text-foreground resize-none min-h-[44px] max-h-[200px] placeholder:text-muted-foreground/50",disabled:h}),o.jsx("button",{type:"submit",disabled:!u.trim()||h,className:"p-2.5 mb-1 bg-primary text-primary-foreground rounded-xl shadow-md hover:bg-primary/90 disabled:opacity-40 disabled:cursor-not-allowed transition-all shrink-0 cursor-pointer",children:h?o.jsx(ma,{size:18,className:"animate-spin"}):o.jsx(GC,{size:18})})]})})})]})}function Z6({sources:t,onClose:e}){return!t||t.length===0?null:o.jsx(_p,{children:o.jsxs(Ro.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:"flex flex-col h-full",children:[o.jsxs("div",{className:"p-4 border-b border-border flex items-center justify-between bg-surface/15",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground/80",children:[o.jsx(Rk,{size:16,className:"text-secondary"}),o.jsx("span",{children:"Retrieved Context"})]}),o.jsx("button",{onClick:e,className:"p-1 hover:bg-surface rounded-md text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:o.jsx(zn,{size:14})})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3 scrollbar-on-hover",children:t.map((s,i)=>{const l=Math.round(s.similarity*100);return o.jsxs("div",{className:"p-3 bg-surface/20 hover:bg-surface/50 border border-border rounded-xl transition-all group",children:[o.jsxs("div",{className:"flex justify-between items-start mb-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-bold",children:[o.jsx("span",{className:"flex items-center justify-center w-4 h-4 bg-primary/10 text-primary rounded",children:i+1}),o.jsxs("span",{className:`px-1.5 py-0.5 rounded border ${l>=80?"bg-amber-500/10 text-amber-600 border-amber-500/20":"bg-blue-500/10 text-blue-500 border-blue-500/20"}`,children:[l,"% Match"]})]}),o.jsx("button",{onClick:()=>{console.log("Open Ingestion ID:",s.ingestion_id)},className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-muted-foreground hover:text-primary transition-opacity focus-visible:ring-2 focus-visible:ring-primary/40 rounded cursor-pointer",title:"View Source Document",children:o.jsx(Uw,{size:12})})]}),o.jsxs("div",{className:"text-[11px] text-muted-foreground leading-relaxed line-clamp-4 font-mono bg-black/5 p-2 rounded-lg border border-border/40",children:['"',s.content,'"']})]},i)})}),o.jsxs("div",{className:"p-3 border-t border-border bg-surface/20 text-[10px] text-center text-muted-foreground/50 font-medium",children:[t.length," document chunk",t.length!==1?"s":""," retrieved"]})]})})}function eP(){const[t,e]=v.useState(null),[s,i]=v.useState([]),[l,u]=v.useState(!1),[d,h]=v.useState(0),m=v.useCallback(y=>{e(y),h(x=>x+1)},[]),p=v.useCallback(y=>{i(y),y.length>0&&u(!0)},[]);return o.jsxs("div",{className:"flex w-full h-[calc(100vh-15rem)] min-h-[540px] gap-4 overflow-hidden animate-in fade-in duration-500",children:[o.jsx("div",{className:"w-64 shrink-0 flex flex-col h-full bg-surface/25 backdrop-blur-xl border border-border rounded-xl overflow-hidden shadow-sm",children:o.jsx(W6,{activeSessionId:t,onSelectSession:e,refreshTrigger:d})}),o.jsx("div",{className:"flex-1 min-w-0 flex flex-col h-full bg-surface/60 rounded-xl overflow-hidden border border-border relative shadow-sm",children:o.jsx(Q6,{sessionId:t,onContextUpdate:p,onSessionCreated:m})}),l&&o.jsx("div",{className:"w-80 shrink-0 flex flex-col h-full bg-surface/25 backdrop-blur-xl border border-border rounded-xl overflow-hidden shadow-sm",children:o.jsx(Z6,{sources:s,onClose:()=>u(!1)})})]})}const Aj=v.createContext(void 0);function tP({children:t}){const[e,s]=v.useState(!1),i=v.useCallback(()=>s(!0),[]),l=v.useCallback(()=>s(!1),[]),u=v.useMemo(()=>({isExpanded:e,setIsExpanded:s,openTerminal:i,closeTerminal:l}),[e,i,l]);return o.jsx(Aj.Provider,{value:u,children:t})}function nP(){const t=v.useContext(Aj);if(t===void 0)throw new Error("useTerminal must be used within a TerminalProvider");return t}const sP=/(https?:\/\/[^\s<>"'`]+)/g;function If(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Rj(t){if(typeof t!="string"||t.trim().length===0)return null;try{const e=new URL(t.trim());return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.toString()}catch{return null}}function aP(t){if(!If(t)||!If(t.remediation))return null;const e=t.remediation,s=typeof e.title=="string"?e.title.trim():"",i=typeof e.summary=="string"?e.summary.trim():"",l=typeof e.code=="string"?e.code.trim():"",u=Array.isArray(e.steps)?e.steps.filter(h=>typeof h=="string").map(h=>h.trim()).filter(Boolean):[],d=Array.isArray(e.links)?e.links.filter(If).map(h=>{const m=Rj(h.url);return m?{label:typeof h.label=="string"&&h.label.trim().length>0?h.label.trim():"Open help link",url:m}:null}).filter(h=>h!==null):[];return!s&&!i&&!l&&u.length===0&&d.length===0?null:{...s?{title:s}:{},...i?{summary:i}:{},...l?{code:l}:{},steps:u,links:d}}function Kc(t){const e=[];let s=0;for(const i of t.matchAll(sP)){const l=i[0]??"",u=i.index??0,d=u+l.length;u>s&&e.push(o.jsx("span",{children:t.slice(s,u)},`txt-${s}-${u}`));const h=Rj(l);h?e.push(o.jsx("a",{href:h,target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 decoration-current/50 hover:decoration-current",onClick:m=>m.stopPropagation(),children:h},`url-${u}-${h}`)):e.push(o.jsx("span",{children:l},`txt-${u}-${d}`)),s=d}return s<t.length&&e.push(o.jsx("span",{children:t.slice(s)},`txt-${s}-${t.length}`)),e.length>0?o.jsx(o.Fragment,{children:e}):t}function iP(){const t=un(),{isExpanded:e,openTerminal:s,closeTerminal:i}=nP(),[l,u]=v.useState([]),[d,h]=v.useState(new Set),[m,p]=v.useState(!1),y=v.useRef(null);v.useEffect(()=>{let _=!0;const E=async()=>{if(!t)return;const{data:{user:k}}=await t.auth.getUser();if(!k)return;const{data:M,error:P}=await t.from("processing_events").select("*").eq("user_id",k.id).order("created_at",{ascending:!1}).limit(50);if(M&&_){u(M);const B=new Set;M.forEach(R=>{R.event_type==="error"&&R.details?.error&&B.add(R.id)}),h(B)}},C=async()=>{if(!t)return null;const{data:{user:k}}=await t.auth.getUser();return k?t.channel("processing_events_realtime").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${k.id}`},M=>{const P=M.new;_&&(P.event_type==="error"&&P.details?.error&&h(B=>new Set(B).add(P.id)),P.details?.is_completion||(P.event_type==="error"||P.agent_state==="action"||P.agent_state==="extraction"||P.details?.is_high_intent===!0)&&s(),u(B=>{const R=[P,...B];return P.details?.is_completion&&setTimeout(()=>{_&&i()},3e3),R.length>100?R.slice(0,100):R}),p(!0),setTimeout(()=>p(!1),500))}).subscribe():null};E();const A=C();return()=>{_=!1,A.then(k=>{k&&t&&t.removeChannel(k)})}},[t,s,i]);const x=(_,E)=>{E.stopPropagation(),h(C=>{const A=new Set(C);return A.has(_)?A.delete(_):A.add(_),A})},w=_=>{switch(_.event_type){case"error":return"border-l-rose-500/50 bg-rose-500/5 text-rose-200";case"action":return"border-l-indigo-500/50 bg-indigo-500/5 text-indigo-200";case"analysis":return"border-l-amber-500/50 bg-amber-500/5 text-amber-200";default:return"border-l-emerald-500/30 text-emerald-100 hover:bg-white/5"}},j=_=>{if(!_)return o.jsx(dr,{className:"w-3.5 h-3.5"});const E=_.toLowerCase();return E.includes("triage")?o.jsx(oC,{className:"w-3.5 h-3.5"}):E.includes("extraction")?o.jsx(Pw,{className:"w-3.5 h-3.5"}):E.includes("matching")?o.jsx($m,{className:"w-3.5 h-3.5"}):E.includes("action")?o.jsx(qw,{className:"w-3.5 h-3.5"}):E.includes("completed")?o.jsx(os,{className:"w-3.5 h-3.5"}):E.includes("error")?o.jsx(uu,{className:"w-3.5 h-3.5"}):o.jsx(Bm,{className:"w-3.5 h-3.5"})},T=_=>_||"System",S=_=>{const E=_.details?.action||_.details?.error;if(typeof E=="string"&&E.trim().length>0)return E;const C=JSON.stringify(_.details);return typeof C=="string"&&C.trim().length>0?C:"Event received."};return e?o.jsxs("div",{className:"fixed bottom-4 right-4 z-50 w-[450px] bg-[#0A0D14] border border-white/10 rounded-xl shadow-2xl flex flex-col overflow-hidden transition-all duration-300 ease-out h-[600px] max-h-[85vh]",children:[o.jsxs("div",{className:"px-4 py-3 border-b border-white/10 bg-white/5 flex items-center justify-between shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Io,{className:"w-4 h-4 text-emerald-400"}),o.jsx("h3",{className:"font-semibold text-sm text-zinc-100 uppercase tracking-widest",children:"Live Trace"}),o.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20 ml-2",children:[o.jsx("div",{className:`w-1.5 h-1.5 rounded-full ${m?"bg-emerald-400 animate-pulse":"bg-emerald-500/50"}`}),o.jsx("span",{className:"text-[9px] font-medium text-emerald-400/80 uppercase tracking-widest",children:m?"Streaming":"Connected"})]})]}),o.jsx("button",{onClick:_=>{_.stopPropagation(),i()},className:"p-1.5 hover:bg-white/10 rounded-md text-zinc-400 hover:text-white transition-colors",children:o.jsx($w,{className:"w-4 h-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-2 font-mono text-xs flex flex-col gap-1.5 custom-scrollbar bg-[#05070A]",children:[l.length===0?o.jsxs("div",{className:"flex items-center justify-center h-full text-zinc-500 flex-col gap-2",children:[o.jsx(dr,{className:"w-6 h-6 opacity-20"}),o.jsx("span",{className:"text-sm",children:"Waiting for ingestion events..."})]}):l.map(_=>{const E=d.has(_.id),C=aP(_.details);return o.jsx("div",{className:`border-l-2 pl-3 py-2 pr-2 rounded-r-md transition-colors ${w(_)}`,children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"shrink-0 pt-0.5 opacity-60",children:j(_.agent_state)}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:new Date(_.created_at).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}),o.jsx("span",{className:"text-[10px] font-bold tracking-wider uppercase opacity-80 shrink-0",children:T(_.agent_state)}),_.ingestion_id&&o.jsx("span",{className:"text-[10px] text-zinc-500 truncate ml-auto uppercase",title:_.ingestion_id,children:_.ingestion_id.substring(0,8)})]}),o.jsx("div",{className:"leading-relaxed break-words whitespace-pre-wrap",children:Kc(S(_))}),_.event_type==="error"&&C&&o.jsxs("div",{className:"mt-2 rounded border border-amber-400/30 bg-amber-500/10 px-2.5 py-2 text-[10px] text-amber-100 space-y-1.5",children:[o.jsx("p",{className:"font-semibold uppercase tracking-wider text-[9px] text-amber-200",children:"Suggested Fix"}),C.title&&o.jsx("p",{className:"font-semibold text-amber-100",children:Kc(C.title)}),C.summary&&o.jsx("p",{className:"text-amber-100/90",children:Kc(C.summary)}),C.code&&o.jsxs("p",{className:"text-amber-200/90",children:["Code: ",C.code]}),C.steps.length>0&&o.jsx("ol",{className:"list-decimal pl-4 space-y-1 text-amber-100/90",children:C.steps.map(A=>o.jsx("li",{children:Kc(A)},`${_.id}-fix-step-${A}-${A.length}`))}),C.links.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1.5 pt-0.5",children:C.links.map(A=>o.jsx("a",{href:A.url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center rounded border border-amber-300/40 px-2 py-1 text-[9px] font-semibold uppercase tracking-wider text-amber-100 hover:bg-amber-300/10",onClick:k=>k.stopPropagation(),children:A.label},`${_.id}-fix-link-${A.url}`))})]}),_.event_type!=="info"&&_.details&&Object.keys(_.details).length>(_.details.action?1:0)&&o.jsx("div",{className:"mt-2 text-[10px]",children:_.event_type==="error"?o.jsxs("div",{className:"bg-rose-950/30 rounded border border-rose-500/20 overflow-hidden",children:[o.jsxs("button",{className:"w-full text-left px-2 py-1 flex justify-between items-center hover:bg-rose-500/10 text-rose-300 font-semibold uppercase tracking-wider text-[9px]",onClick:A=>x(_.id,A),children:[o.jsx("span",{children:"Error Details"}),o.jsx("span",{className:"opacity-50",children:E?"Hide":"Show"})]}),E&&o.jsx("pre",{className:"p-2 border-t border-rose-500/20 overflow-x-auto text-rose-200/80 custom-scrollbar",children:JSON.stringify(_.details,null,2)})]}):o.jsx("div",{className:"bg-black/20 rounded border border-white/5 p-2 overflow-x-auto text-white/50 custom-scrollbar",children:o.jsx("pre",{children:JSON.stringify(Object.fromEntries(Object.entries(_.details).filter(([A])=>A!=="action")),null,2)})})})]})]})},_.id)}),o.jsx("div",{ref:y,className:"h-4 shrink-0"})]}),o.jsxs("div",{className:"shrink-0 p-3 bg-white/5 border-t border-white/10 flex items-center gap-2 text-zinc-500 text-xs",children:[o.jsx("span",{className:"text-emerald-500/50 font-bold",children:"➜"}),o.jsx("span",{className:"animate-pulse",children:"_"})]})]}):o.jsxs("button",{type:"button",className:"fixed bottom-4 right-4 z-50 bg-[#0A0D14] border border-white/10 rounded-full py-2 px-4 shadow-xl flex items-center gap-3 cursor-pointer transition-all hover:bg-[#11141D] hover:border-white/20",onClick:s,children:[o.jsxs("div",{className:"relative",children:[o.jsx(Io,{className:`w-4 h-4 ${m?"text-emerald-400":"text-zinc-400"}`}),m&&o.jsx("div",{className:"absolute inset-0 bg-emerald-400/20 blur-sm rounded-full animate-pulse"})]}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-xs font-medium text-zinc-200",children:"Live Trace"}),o.jsx("span",{className:"text-[10px] text-zinc-500 leading-none mt-0.5",children:l.length>0?T(l[0].agent_state):"Idle"})]}),o.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500/50 shadow-[0_0_8px_rgba(16,185,129,0.5)] ml-1"})]})}function rP(){const t=v.useMemo(()=>$o(),[]),[e,s]=v.useState("dashboard"),[i,l]=v.useState(null),[u,d]=v.useState(!t),[h,m]=v.useState(!1),[p,y]=v.useState("not_checked"),[x,w]=v.useState("Folio ready. Run setup to configure runtime contracts."),[j,T]=v.useState(t),S=jA(),[_,E]=v.useState(!1),[C,A]=v.useState(0),[k,M]=v.useState("unknown"),[P,B]=v.useState("unknown"),[R,I]=v.useState(null),[te,ie]=v.useState(null),[fe,Ne]=v.useState(!1),[ye,se]=v.useState(()=>{const q=localStorage.getItem("folio_migration_snoozed_until");return q?new Date(q):null}),[V,F]=v.useState(null),J=v.useMemo(()=>j?zm(j.url,j.anonKey,{auth:{autoRefreshToken:!0,persistSession:!0}}):null,[j]);v.useEffect(()=>{if(!J){B("unknown"),I(null);return}const{data:q}=J.auth.onAuthStateChange((pe,oe)=>{B(oe?.user?"authenticated":"anonymous"),I(oe?.user?.email??null),A(ze=>ze+1)});return()=>{q.subscription.unsubscribe()}},[J]),v.useEffect(()=>{let q=!1;async function pe(ze,Be){const kt=Promise.resolve(ze);let et=null;const ce=new Promise((Fe,he)=>{et=setTimeout(()=>{he(new Error(`Operation timed out after ${Be}ms`))},Be)});try{return await Promise.race([kt,ce])}finally{et&&clearTimeout(et)}}async function oe(){if(!J){M("unknown"),B("unknown"),I(null),ie(null),F(null);return}E(!0),F(null);try{const{data:ze,error:Be}=await pe(J.from("init_state").select("is_initialized").single(),12e3);if(Be)if(Be.code==="42P01")M("missing_view");else throw M("error"),new Error(Be.message||"Failed to query init_state");else{const Fe=Number(ze.is_initialized??0)>0;M(Fe?"initialized":"empty")}const{data:kt,error:et}=await pe(J.auth.getSession(),12e3);if(et)B("error"),I(null);else{const Fe=kt.session?.user??null;B(Fe?"authenticated":"anonymous"),I(Fe?.email??null)}const ce=await pe(Qw(J),12e3);ie(ce)}catch(ze){const Be=ze instanceof Error?ze.message:String(ze);q||(F(Be),w(`Bootstrap check failed: ${Be}`))}finally{q||E(!1)}}return oe(),()=>{q=!0}},[J,C]);function ge(){const q=$o();T(q),d(!1),w("Setup complete. Foundation runtime is configured."),y("not_checked"),A(pe=>pe+1)}function ne(){wA(),T(null),M("unknown"),B("unknown"),I(null),ie(null),F(null),d(!0),w("Stored setup was cleared. Run setup wizard again."),y("not_checked"),A(q=>q+1)}function D(){A(q=>q+1)}const L=q=>{se(q),localStorage.setItem("folio_migration_snoozed_until",q.toISOString())},W=v.useMemo(()=>!(!te?.needsMigration||ye&&ye>new Date),[te,ye]),ee=[{id:"dashboard",label:"Dashboard",icon:m0},{id:"chat",label:"Chat",icon:cu},{id:"funnel",label:"Funnel",icon:Bw},{id:"policies",label:"Policies",icon:Hw},{id:"config",label:"Configuration",icon:$m}];return u||!j?o.jsx("div",{className:"min-h-screen bg-background",children:o.jsx(m5,{open:u||!j,canClose:!!j,onComplete:ge})}):k==="empty"||k==="missing_view"||P!=="authenticated"?_&&k==="unknown"?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(rt,{className:"w-10 h-10 animate-spin text-primary opacity-50"}),o.jsx("p",{className:"text-[10px] font-black uppercase tracking-[0.3em] text-muted-foreground animate-pulse",children:"Initializing Engine..."})]})}):o.jsx(l6,{supabase:J,initStatus:k,onSuccess:D,onResetConfigs:ne}):o.jsx(tP,{children:o.jsxs("div",{className:"min-h-screen bg-background text-foreground selection:bg-primary/10 flex flex-col font-sans animate-in fade-in duration-1000",children:[W&&te&&o.jsx(C6,{status:te,onSnooze:L,onOpenModal:()=>Ne(!0)}),te&&o.jsx(A6,{open:fe,onOpenChange:Ne,status:te,onSnooze:L}),o.jsx("header",{className:ve("border-b bg-background/80 backdrop-blur-xl sticky top-0 z-50 transition-all duration-500",W&&"mt-24 sm:mt-20"),children:o.jsxs("div",{className:"container max-w-[1400px] mx-auto px-8 h-20 flex items-center",children:[o.jsxs("div",{className:"flex items-center gap-3 w-[280px]",children:[o.jsx("div",{className:"w-9 h-9 flex items-center justify-center",children:o.jsx(ou,{className:"w-8 h-8"})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h1",{className:"text-xl font-bold tracking-tight text-foreground/90",children:"Folio"}),o.jsx("div",{className:"flex items-center",children:o.jsxs("span",{className:"relative flex h-2 w-2",children:[o.jsx("span",{className:ve("animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",p==="ok"?"bg-emerald-400":"bg-primary/40")}),o.jsx("span",{className:ve("relative inline-flex rounded-full h-2 w-2",p==="ok"?"bg-emerald-500":"bg-primary/60")})]})})]})]}),o.jsx("nav",{className:"flex-1 hidden md:flex items-center justify-center gap-2",children:ee.map(q=>o.jsxs("button",{onClick:()=>s(q.id),className:ve("flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold transition-all duration-300",e===q.id?"bg-primary/10 text-primary shadow-sm":"text-muted-foreground/80 hover:bg-muted/60 hover:text-foreground"),children:[o.jsx(q.icon,{className:ve("w-4.5 h-4.5",e===q.id?"text-primary":"text-muted-foreground/60")}),q.label]},q.id))}),o.jsxs("div",{className:"flex items-center justify-end gap-5 w-[280px]",children:[o.jsxs("div",{className:"hidden lg:flex items-center gap-2 px-3 py-1.5 bg-muted/40 rounded-full border border-border/40 cursor-pointer hover:bg-muted/60 transition-colors",children:[o.jsx("img",{src:"https://flagcdn.com/w40/us.png",className:"w-4 h-3 rounded-sm opacity-80",alt:"EN"}),o.jsx("span",{className:"text-[10px] font-extrabold tracking-widest text-muted-foreground",children:"EN"})]}),o.jsxs(ae,{variant:"ghost",size:"icon",className:ve("rounded-full h-9 w-9 transition-all relative group",te?.needsMigration?"text-red-500 hover:bg-red-500/10":"text-muted-foreground hover:bg-muted/60"),onClick:()=>m(!0),children:[o.jsx(dr,{className:ve("w-5 h-5",te?.needsMigration&&"animate-pulse")}),te?.needsMigration&&o.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-red-500 ring-4 ring-red-500/20 animate-ping"})]}),o.jsx(e1,{}),o.jsx("div",{className:"w-10 h-10 rounded-full overflow-hidden border-2 border-background shadow-lg cursor-pointer ring-1 ring-border/20",onClick:()=>s("account"),children:o.jsx("div",{className:"w-full h-full bg-primary flex items-center justify-center text-primary-foreground font-black text-xs",children:R?.charAt(0).toUpperCase()||"A"})})]})]})}),o.jsxs("main",{className:"flex-1 w-full px-6 py-12 mx-auto max-w-[1600px]",children:[V&&o.jsxs(jn,{variant:"destructive",className:"mb-10 animate-in fade-in slide-in-from-top-4 duration-500",children:[o.jsx(Sn,{className:"h-5 w-5"}),o.jsx(Hm,{className:"font-bold",children:"Protocol Connection Failure"}),o.jsx(_n,{className:"text-[13px] opacity-90",children:V})]}),e==="dashboard"&&o.jsx(AA,{configSnapshot:j,configSource:S,setActivePage:s}),e==="chat"&&o.jsx(eP,{}),e==="funnel"&&o.jsx(X6,{onComposePolicyForDoc:q=>{l(q),s("policies")}}),e==="policies"&&o.jsx(O6,{initialCompose:i,onInitialConsumed:()=>l(null)}),e==="config"&&o.jsx(k6,{}),e==="account"&&o.jsx(JA,{supabase:J,sessionEmail:R,sessionStatus:P,initStatus:k,configSnapshot:j,configSource:S,onRefresh:D,onLaunchSetup:()=>d(!0),onResetSetup:ne})]}),o.jsx(iP,{}),o.jsx("div",{className:"fixed bottom-6 left-6 z-[60]",children:o.jsx(ae,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full shadow-xl bg-background border border-border/40 text-muted-foreground hover:text-primary hover:scale-110 transition-all",children:o.jsx(m0,{className:"w-6 h-6"})})}),o.jsx("footer",{className:"border-t bg-card/20 py-10 mt-auto",children:o.jsxs("div",{className:"container max-w-7xl mx-auto px-8 flex items-center justify-between text-[11px] text-muted-foreground font-bold uppercase tracking-[0.2em] opacity-40",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{children:"Core Foundation Protocol"}),o.jsx("div",{className:"w-1 h-1 rounded-full bg-muted-foreground"}),o.jsx("span",{children:"2026"})]}),o.jsxs("div",{className:"flex items-center gap-8",children:[o.jsx("a",{href:"#",className:"hover:text-foreground transition-colors",children:"Whitepaper"}),o.jsx("a",{href:"#",className:"hover:text-foreground transition-colors",children:"Foundation Registry"})]})]})}),o.jsx(WO,{open:h,onOpenChange:m,health:p,isBootstrapping:_,initStatus:k||"unknown",sessionStatus:P||"unknown",migrationStatus:te,onRunMigration:()=>{m(!1),Ne(!0)}})]})})}s2.createRoot(document.getElementById("root")).render(o.jsx(ew.StrictMode,{children:o.jsx(nR,{defaultTheme:"dark",storageKey:"folio-theme",children:o.jsx(d6,{children:o.jsx(f6,{children:o.jsxs(y6,{children:[o.jsx(rP,{}),o.jsx(CA,{})]})})})})}));