1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,630168,e=>{"use strict";var r=e.i(843476),t=e.i(271645);e.i(529225);var o=e.i(972390);let n=(0,t.createContext)(void 0);e.s(["OrganizationProvider",0,function({children:e}){let[a,i]=(0,t.useState)(null),[s,c]=(0,t.useState)([]),[u,l]=(0,t.useState)(!0),f=(0,t.useRef)(null);(0,t.useEffect)(()=>{f.current=(0,o.createBrowserClient)("https://bsemaovjgsrsbbdkzydo.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJzZW1hb3ZqZ3Nyc2JiZGt6eWRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDE3OTY3MTcsImV4cCI6MjA1NzM3MjcxN30.4LHiJ6GGOn6piGDtM_58FSa1j-r9_K5mngg2IGHMEr4")},[]),(0,t.useEffect)(()=>{try{let e=localStorage.getItem("currentOrgId");e&&console.log("Found saved organization ID in localStorage:",e)}catch(e){console.error("Error accessing localStorage:",e)}},[]);let g=(0,t.useCallback)(async()=>{if(f.current)try{l(!0);let{data:e,error:r}=await f.current.from("organizations").select("*").order("name",{ascending:!0});if(r){console.error("Error fetching organizations:",r),l(!1);return}let t=e?.map(e=>({...e,id:e.org_id}))||[];c(t);try{let e=localStorage.getItem("currentOrgId");if(e&&t.length>0){let r=t.find(r=>r.org_id===e);if(r){i(t=>{if(t?.org_id!==e){console.log("Restoring saved organization:",r.name);try{localStorage.setItem("currentOrgId",r.org_id),console.log("Saved organization ID to localStorage:",r.org_id)}catch(e){console.error("Error managing localStorage:",e)}return r}return t}),l(!1);return}console.log("Saved organization ID not found in available organizations")}}catch(e){console.error("Error accessing localStorage:",e)}i(e=>{if(t.length>0&&!e){console.log("Setting default organization:",t[0].name);try{localStorage.setItem("currentOrgId",t[0].org_id),console.log("Saved organization ID to localStorage:",t[0].org_id)}catch(e){console.error("Error managing localStorage:",e)}return t[0]}return e})}catch(e){console.error("Unexpected error fetching organizations:",e)}finally{l(!1)}},[]);(0,t.useEffect)(()=>{f.current&&g()},[g]);let d=async(e,r)=>{if(!f.current)return null;try{let{data:t,error:o}=await f.current.from("organizations").insert([{name:e,description:r,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}]).select();if(o)return console.error("Error creating organization:",o),null;if(t&&t.length>0){let e={...t[0],id:t[0].org_id};return c([...s,e]),e}return null}catch(e){return console.error("Unexpected error creating organization:",e),null}};return(0,r.jsx)(n.Provider,{value:{currentOrg:a,setCurrentOrg:e=>{i(e);try{e?(localStorage.setItem("currentOrgId",e.org_id),console.log("Saved organization ID to localStorage:",e.org_id)):(localStorage.removeItem("currentOrgId"),console.log("Cleared organization ID from localStorage"))}catch(e){console.error("Error managing localStorage:",e)}},loading:u,organizations:s,fetchOrganizations:g,createOrganization:d},children:e})},"useOrganization",0,function(){let e=(0,t.useContext)(n);if(void 0===e)throw Error("useOrganization must be used within an OrganizationProvider");return e}])},462819,(e,r,t)=>{"use strict";t.parse=function(e,r){if("string"!=typeof e)throw TypeError("argument str must be a string");var t={},o=e.length;if(o<2)return t;var a=r&&r.decode||f,i=0,s=0,c=0;do{if(-1===(s=e.indexOf("=",i)))break;if(-1===(c=e.indexOf(";",i)))c=o;else if(s>c){i=e.lastIndexOf(";",s-1)+1;continue}var g=u(e,i,s),d=l(e,s,g),p=e.slice(g,d);if(!n.call(t,p)){var h=u(e,s+1,c),y=l(e,c,h);34===e.charCodeAt(h)&&34===e.charCodeAt(y-1)&&(h++,y--);var m=e.slice(h,y);t[p]=function(e,r){try{return r(e)}catch(r){return e}}(m,a)}i=c+1}while(i<o)return t},t.serialize=function(e,r,t){var n=t&&t.encode||encodeURIComponent;if("function"!=typeof n)throw TypeError("option encode is invalid");if(!a.test(e))throw TypeError("argument name is invalid");var u=n(r);if(!i.test(u))throw TypeError("argument val is invalid");var l=e+"="+u;if(!t)return l;if(null!=t.maxAge){var f=Math.floor(t.maxAge);if(!isFinite(f))throw TypeError("option maxAge is invalid");l+="; Max-Age="+f}if(t.domain){if(!s.test(t.domain))throw TypeError("option domain is invali
1d");l+="; Domain="+t.domain}if(t.path){if(!c.test(t.path))throw TypeError("option path is invalid");l+="; Path="+t.path}if(t.expires){var g,d=t.expires;if(g=d,"[object Date]"!==o.call(g)||isNaN(d.valueOf()))throw TypeError("option expires is invalid");l+="; Expires="+d.toUTCString()}if(t.httpOnly&&(l+="; HttpOnly"),t.secure&&(l+="; Secure"),t.partitioned&&(l+="; Partitioned"),t.priority)switch("string"==typeof t.priority?t.priority.toLowerCase():t.priority){case"low":l+="; Priority=Low";break;case"medium":l+="; Priority=Medium";break;case"high":l+="; Priority=High";break;default:throw TypeError("option priority is invalid")}if(t.sameSite)switch("string"==typeof t.sameSite?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"none":l+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return l};var o=Object.prototype.toString,n=Object.prototype.hasOwnProperty,a=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,i=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,s=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,c=/^[\u0020-\u003A\u003D-\u007E]*$/;function u(e,r,t){do{var o=e.charCodeAt(r);if(32!==o&&9!==o)return r}while(++r<t)return t}function l(e,r,t){for(;r>t;){var o=e.charCodeAt(--r);if(32!==o&&9!==o)return r+1}return t}
1function f(e){return -1!==e.indexOf("%")?decodeURIComponent(e):e}},290571,e=>{"use strict";var r=function(e,t){return(r=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,r){e.__proto__=r}||function(e,r){for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=r[t])})(e,t)};function t(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function o(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}var o=function(){return(o=Object.assign||function(e){for(var r,t=1,o=arguments.length;t<o;t++)for(var n in r=arguments[t])Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n]);return e}).apply(this,arguments)};function n(e,r){var t={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&0>r.indexOf(o)&&(t[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,o=Object.getOwnPropertySymbols(e);n<o.length;n++)0>r.indexOf(o[n])&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(t[o[n]]=e[o[n]]);return t}function a(e,r,t,o){var n,a=arguments.length,i=a<3?r:null===o?o=Object.getOwnPropertyDescriptor(r,t):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,r,t,o);else for(var s=e.length-1;s>=0;s--)(n=e[s])&&(i=(a<3?n(i):a>3?n(r,t,i):n(r,t))||i);return a>3&&i&&Object.defineProperty(r,t,i),i}function i(e,r){return function(t,o){r(t,o,e)}}function s(e,r,t,o,n,a){function i(e){if(void 0!==e&&"function"!=typeof e)throw TypeError("Function expected");return e}for(var s,c=o.kind,u="getter"===c?"get":"setter"===c?"set":"value",l=!r&&e?o.static?e:e.prototype:null,f=r||(l?Object.getOwnPropertyDescriptor(l,o.name):{}),g=!1,d=t.length-1;d>=0;d--){var p={};for(var h in o)p[h]="access"===h?{}:o[h];for(var h in o.access)p.access[h]=o.access[h];p.addInitializer=function(e){if(g)throw TypeError("Cannot add initializers after decoration has completed");a.push(i(e||null))};var y=(0,t[d])("accessor"===c?{get:f.get,set:f.set}:f[u],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw TypeError("Object expected");(s=i(y.get))&&(f.get=s),(s=i(y.set))&&(f.set=s),(s=i(y.init))&&n.unshift(s)}else(s=i(y))&&("field"===c?n.unshift(s):f[u]=s)}l&&Object.defineProperty(l,o.name,f),g=!0}function c(e,r,t){for(var o=arguments.length>2,n=0;n<r.length;n++)t=o?r[n].call(e,t):r[n].call(e);return o?t:void 0}function u(e){return"symbol"==typeof e?e:"".concat(e)}function l(e,r,t){return"symbol"==typeof r&&(r=r.description?"[".concat(r.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:t?"".concat(t," ",r):r})}function f(e,r){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,r)}function g(e,r,t,o){return new(t||(t=Promise))(function(n,a){function i(e){try{c(o.next(e))}catch(e){a(e)}}function s(e){try{c(o.throw(e))}catch(e){a(e)}}function c(e){var r;e.done?n(e.value):((r=e.value)instanceof t?r:new t(function(e){e(r)})).then(i,s)}c((o=o.apply(e,r||[])).next())})}function d(e,r){var t,o,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=s(0),i.throw=s(1),i.return=s(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){var u=[s,c];if(t)throw TypeError("Generator is already executing.");for(;i&&(i=0,u[0]&&(a=0)),a;)try{if(t=1,o&&(n=2&u[0]?o.return:u[0]?o.throw||((n=o.return)&&n.call(o),0):o.next)&&!(n=n.call(o,u[1])).done)return n;switch(o=0,n&&(u=[2&u[0],n.value]),u[0]){case 0:case 1:n=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,o=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===u[0]||2===u[0])){a=0;continue}if(3===u[0]&&(!n||u[1]>n[0]&&u[1]<n[3])){a.label=u[1];break}if(6===u[0]&&a.label<n[1]){a.label=n[1],n=u;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(u);break}n[2]&&a.ops.pop(),a.trys.pop();continue}u=r.call(e,a)}catch(e){u=[6,e],o=0}finally{t=n=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var p=Object.create?function(e,r,t,o){void 0===o&&(o=t);var n=Object.getOwnPropertyDescriptor(r,t);
1(!n||("get"in n?!r.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,o,n)}:function(e,r,t,o){void 0===o&&(o=t),e[o]=r[t]};function h(e,r){for(var t in e)"default"===t||Object.prototype.hasOwnProperty.call(r,t)||p(r,e,t)}function y(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,n,a=t.call(e),i=[];try{for(;(void 0===r||r-- >0)&&!(o=a.next()).done;)i.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(t=a.return)&&t.call(a)}finally{if(n)throw n.error}}return i}function b(){for(var e=[],r=0;r<arguments.length;r++)e=e.concat(m(arguments[r]));return e}function _(){for(var e=0,r=0,t=arguments.length;r<t;r++)e+=arguments[r].length;for(var o=Array(e),n=0,r=0;r<t;r++)for(var a=arguments[r],i=0,s=a.length;i<s;i++,n++)o[n]=a[i];return o}function v(e,r,t){if(t||2==arguments.length)for(var o,n=0,a=r.length;n<a;n++)!o&&n in r||(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return e.concat(o||Array.prototype.slice.call(r))}function w(e){return this instanceof w?(this.v=e,this):new w(e)}function S(e,r,t){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var o,n=t.apply(e,r||[]),a=[];return o=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),i("next"),i("throw"),i("return",function(e){return function(r){return Promise.resolve(r).then(e,u)}}),o[Symbol.asyncIterator]=function(){return this},o;function i(e,r){n[e]&&(o[e]=function(r){return new Promise(function(t,o){a.push([e,r,t,o])>1||s(e,r)})},r&&(o[e]=r(o[e])))}function s(e,r){try{var t;(t=n[e](r)).value instanceof w?Promise.resolve(t.value.v).then(c,u):l(a[0][2],t)}catch(e){l(a[0][3],e)}}function c(e){s("next",e)}function u(e){s("throw",e)}function l(e,r){e(r),a.shift(),a.length&&s(a[0][0],a[0][1])}}function E(e){var r,t;return r={},o("next"),o("throw",function(e){throw e}),o("return"),r[Symbol.iterator]=function(){return this},r;function o(o,n){r[o]=e[o]?function(r){return(t=!t)?{value:w(e[o](r)),done:!1}:n?n(r):r}:n}}function O(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var r,t=e[Symbol.asyncIterator];return t?t.call(e):(e=y(e),r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r);function o(t){r[t]=e[t]&&function(r){return new Promise(function(o,n){var a,i,s;a=o,i=n,s=(r=e[t](r)).done,Promise.resolve(r.value).then(function(e){a({value:e,done:s})},i)})}}}function I(e,r){return Object.defineProperty?Object.defineProperty(e,"raw",{value:r}):e.raw=r,e}var P=Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r},T=function(e){return(T=Object.getOwnPropertyNames||function(e){var r=[];for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[r.length]=t);return r})(e)};function j(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var t=T(e),o=0;o<t.length;o++)"default"!==t[o]&&p(r,e,t[o]);return P(r,e),r}function k(e){return e&&e.__esModule?e:{default:e}}function A(e,r,t,o){if("a"===t&&!o)throw TypeError("Private accessor was defined without a getter");if("function"==typeof r?e!==r||!o:!r.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?o:"a"===t?o.call(e):o?o.value:r.get(e)}function D(e,r,t,o,n){if("m"===o)throw TypeError("Private method is not writable");if("a"===o&&!n)throw TypeError("Private accessor was defined without a setter");if("function"==typeof r?e!==r||!n:!r.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,t):n?n.value=t:r.set(e,t),t}function C(e,r){if(null===r||"object"!=typeof r&&"function"!=typeof r)throw TypeError("Cannot use 'in' operator on non-object");return"function"==typeof e?r===e:e.has(r)}function x(e,r,t){if(null!=r){var o,n;if("object"!=typeof r&&"function"!=typeof r)throw TypeError("Object expected.");
1if(t){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");o=r[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");o=r[Symbol.dispose],t&&(n=o)}if("function"!=typeof o)throw TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:r,dispose:o,async:t})}else t&&e.stack.push({async:!0});return r}var z="function"==typeof SuppressedError?SuppressedError:function(e,r,t){var o=Error(t);return o.name="SuppressedError",o.error=e,o.suppressed=r,o};function N(e){function r(r){e.error=e.hasError?new z(r,e.error,"An error was suppressed during disposal."):r,e.hasError=!0}var t,o=0;return function n(){for(;t=e.stack.pop();)try{if(!t.async&&1===o)return o=0,e.stack.push(t),Promise.resolve().then(n);if(t.dispose){var a=t.dispose.call(t.value);if(t.async)return o|=2,Promise.resolve(a).then(n,function(e){return r(e),n()})}else o|=1}catch(e){r(e)}if(1===o)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}function R(e,r){return"string"==typeof e&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,t,o,n,a){return t?r?".jsx":".js":!o||n&&a?o+n+"."+a.toLowerCase()+"js":e}):e}let J={__extends:t,__assign:o,__rest:n,__decorate:a,__param:i,__esDecorate:s,__runInitializers:c,__propKey:u,__setFunctionName:l,__metadata:f,__awaiter:g,__generator:d,__createBinding:p,__exportStar:h,__values:y,__read:m,__spread:b,__spreadArrays:_,__spreadArray:v,__await:w,__asyncGenerator:S,__asyncDelegator:E,__asyncValues:O,__makeTemplateOb
1ject:I,__importStar:j,__importDefault:k,__classPrivateFieldGet:A,__classPrivateFieldSet:D,__classPrivateFieldIn:C,__addDisposableResource:x,__disposeResources:N,__rewriteRelativeImportExtension:R};e.s(["__addDisposableResource",0,x,"__assign",()=>o,"__asyncDelegator",0,E,"__asyncGenerator",0,S,"__asyncValues",0,O,"__await",0,w,"__awaiter",0,g,"__classPrivateFieldGet",0,A,"__classPrivateFieldIn",0,C,"__classPrivateFieldSet",0,D,"__createBinding",0,p,"__decorate",0,a,"__disposeResources",0,N,"__esDecorate",0,s,"__exportStar",0,h,"__extends",0,t,"__generator",0,d,"__importDefault",0,k,"__importStar",0,j,"__makeTemplateObject",0,I,"__metadata",0,f,"__param",0,i,"__propKey",0,u,"__read",0,m,"__rest",0,n,"__rewriteRelativeImportExtension",0,R,"__runInitializers",0,c,"__setFunctionName",0,l,"__spread",0,b,"__spreadArray",0,v,"__spreadArrays",0,_,"__values",0,y,"default",0,J])},703922,e=>{"use strict";e.i(529225);var r=e.i(972390),t=e.i(271645);let o=null;function n(){return o||(o=(0,r.createBrowserClient)("https://bsemaovjgsrsbbdkzydo.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJzZW1hb3ZqZ3Nyc2JiZGt6eWRvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDE3OTY3MTcsImV4cCI6MjA1NzM3MjcxN30.4LHiJ6GGOn6piGDtM_58FSa1j-r9_K5mngg2IGHMEr4")),o}async function a(){let e=n(),{data:r}=await e.auth.getSession();return r.session?.access_token||null}e.s(["createBrowserSupabaseClient",0,n,"createPKCESupabaseClient",0,function(){return n()},"getCurrentAccessToken",0,a,"useSupabase",0,function(){let[e]=(0,t.useState)(()=>n()),[r]=(0,t.useState)(!0);return{client:e,isReady:r}}])},618566,(e,r,t)=>{r.exports=e.r(976562)},894746,458324,e=>{"use strict";var r=e.i(843476),t=e.i(271645),o=e.i(703922),n=e.i(630168),a=e.i(618566);e.i(247167);let i="login_breadcrumbs";function s(e,r){try{let t={step:e,timestamp:Date.now(),data:r},o=sessionStorage.getItem(i),n=o?JSON.parse(o):[];n.push(t);let a=n.slice(-20);sessionStorage.setItem(i,JSON.stringify(a))}catch(e){console.error("Error adding login breadcrumb:",e)}}function c(){try{let e=sessionStorage.getItem(i);return e?JSON.parse(e):[]}catch(e){return console.error("Error getting login breadcrumbs:",e),[]}}function u(){try{sessionStorage.removeItem(i)}catch(e){console.error("Error clearing login breadcrumbs:",e)}}function l(e){try{let r=c();if(0===r.length)return;fetch("/api/monitoring/login-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({breadcrumbs:r,error:e,timestamp:new Date().toISOString(),userAgent:navigator.userAgent,url:window.location.href})}).catch(()=>{})}catch(e){console.error("Error sending breadcrumbs to New Relic:",e)}}function f(e,r){let t=Date.now()-r;return s(`${e}_complete`,{duration_ms:t}),t>8e3&&fetch("/api/monitoring/login-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({warning:"slow_login_step",step:e,duration_ms:t,timestamp:new Date().toISOString()})}).catch(()=>{}),t}e.s(["addLoginBreadcrumb",0,s,"clearLoginBreadcrumbs",0,u,"getLoginBreadcrumbs",0,c,"sendBreadcrumbsToNewRelic",0,l,"trackLoginTiming",0,f],458324);let g={recordEvent(e,r){try{fetch("/api/monitoring/custom-event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:e,attributes:r,timestamp:Date.now()})}).catch(()=>{})}catch(e){}},recordMetric(e,r){},addAttributes(e){},log(e,r,t){}},d=0,p=0,h=!1;function y(){if(!("u"<typeof document)){for(let e of document.cookie.split(";")){let[r]=e.split("="),t=r.trim();(t.startsWith("sb-")||t.includes("supabase"))&&(document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`,document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${window.location.hostname}`)}console.log("[Auth] Cleared Supabase cookies")}}async function m(e,r,t){let o=new AbortController,n=new Promise((e,r)=>{setTimeout(()=>{o.abort(),r(Error("TIMEOUT"))},t)});return Promise.race([fetch(e,{...r,signal:o.signal}),n])}let b=(0,t.createContext)(void 0);e.s(["AuthProvider",0,function({children:e}){let[i,c]=(0,t.useState)(null),[_,v]=(0,t.useState)(!0),[w,S]=(0,t.useState)(null),[E,O]=(0,t.useState)(!1),{setCurrentOrg:I}=(0,n.useOrganization)(),P=(0,a.useRouter)(),T=(0,t.useRef)(null);(0,t.useEffect)(()=>{T.current||(T.current=(0,o.createBrowserSupabaseClient)(),console.log("Initial checkSession starting..."),j())},[]);let j=async(e=0)=>{if(T.current){let r;if(h)return void console.log("[Auth] checkSession already in progress, skipping...");if(h=!0,(r=Date.now())-p>3e4&&(d=0),p=r,d>=2){console.error("[Auth] Max global retry attempts reached. Stopping retry loop."),s("max_retries_reached",{retryCount:d,localRetryCount:e}),y(),v(!1),S("Unable to restore session. Please try logging in again."),h=!1,l({reason:"max_retries_reached",retryCount:d});return}d++,v(!0);try{let r;s("check_session_start",{retryCount:e,globalRetryCount:d}),console.log("Checking for existing session...");let t=T.current;s("get_user_start");let{data:{user:o},error:n}=await t.auth.getUser();if(n){console.error("Error verifying user:",n),s("get_user_error",{error:n?.message}),(n.message?.includes("expired")||n.message?.includes("invalid"))&&(console.log("[Auth] Auth error indicates invalid session, clearing cookies"),y()),A(!1);return}if(!o){console.log("No authenticated user found");let e=!("u"<typeof document)&&document.cookie.split(";").some(e=>{let r=e.trim().split("=")[0];return r.startsWith("sb-")&&r.includes("auth-token")});s("no_user",{hasAuthCookies:e,retryCount:d}),e&&console.log("[Auth] Cookies exist but no user - NOT clearing (may be race condition)"),A(!1);return}s("get_user_success",{userId:o.id}),console.log("User verified:",o.id);let{data:{session:a},error:i}=await t.auth.getSession();(i||!a)&&(console.error("Error getting session after user verified:",i),s("session_error_after_user",{error:i?.message}));try{let{data:{subscription:e}}=t.auth.onAuthStateChange((e,r)=>{if(console.log("Auth state changed:",e),"SIGNED_OUT"===e)A(!1);else if("TOKEN_REFRESHED"===e&&r&&(console.log("Session token refreshed"),r.access_token))try{k(r.access_token)}catch(e){console.error("Error handling token refresh:",e)}});r=e}catch(e){console.error("Error setting up auth state change listener:",e)}if(a?.access_token)try{await k(a.access_token)}catch(e){console.error("Error fetching user data:",e),A(!1)}else{console.error("No access token available in session");let{data:e}=await t.auth.getSession();if(!e.session?.access_token){console.error("Still no access token after refresh"),A(!1);return}try{await k(e.session.access_token)}catch(e){console.error("Error fetching user data:",e),A(!1)}}return()=>{if(r)try{r.unsubscribe()}catch(e){console.error("Error unsubscribing from auth state changes:",e)}}}catch(e){console.error("Unexpected error in checkSession:",e),A(!1)}finally{v(!1),h=!1}}},k=async e=>{console.log("Fetching user data from API...");let r=Date.now();s("fetch_user_data_start");try{let t=await m("/api/auth/user",{headers:{Authorization:`Bearer ${e}`}},8e3).catch(e=>{if(console.error("Network error fetching user data:",e),"TIMEOUT"===e.message||"AbortError"===e.name){let e=Date.now()-r;throw console.error(`[Auth] Fetch user data timed out after ${e}ms`),s("fetch_user_timeout",{elapsed_ms:e}),Error("TIMEOUT")}throw Error("Network error: Unable to connect to the authentication service")});if(!t)throw console.error("No response received from API"),Error("No response from authentication service");if(!t.ok){let e=`API error: ${t.status}`;try{let r=await t.json();e+=` - ${r.error||"Unknown error"}`,console.error("API error:",t.status,r)}catch(e){console.error("Could not parse error response:",e)}throw Error(e)}let o=await t.json().catch(e=>{throw console.error("Error parsing JSON response:",e),Error("Invalid response from authentication service")});if(!o.user)throw console.error("No user data in response:",o),Error("No user data returned from API");console.log("User data fetched successfully"),c(o.user),O(!0),o.organization?(I(o.organization),console.log("Organization set:",o.organization.name)):(console.log("No organization data available - continuing without organization context"),I(null)),console.log("Successfully restored session");let n=f("fetch_user_data",r);return g.recordEvent("login_fetch_user_success",{duration_ms:n,has_organization:!!o.organization}),d=0,o}catch(t){console.error("Error in fetchUserData:",t);let e=t instanceof Error?t.message:"Unknown error";if(s("fetch_user_error",{error:e,elapsed_ms:Date.now()-r}),l({error:e,function:"fetchUserData"}),g.recordEvent("login_fetch_user_error",{error:e,duration_ms:Date.now()-r}),"TIMEOUT"===e||e.includes("timeout"))return S("Login is taking longer than expected. Please try refreshing the page or try again later."),v(!1),console.error("[Auth] Fetch user data timed out. Stopping auth flow to prevent infinite loop."),null;if(d>=2)return S("Unable to complete login. Please try again."),v(!1),null;return A(!1),null}},A=(e=!1)=>{console.log("Authentication failure, clearing state"),s("auth_failure",{globalRetryCount:d,allowRetry:e}),c(null),O(!1),I(null);try{localStorage.removeItem("currentOrgId"),console.log("Cleared organization ID from localStorage")}catch(e){}{let r=window.location.pathname;if(["/login","/auth/reset-password","/signup","/forgot-password"].some(e=>r.startsWith(e))){console.log(`[Auth] On auth page ${r}, not redirecting`),s("no_redirect",{path:r});return}e&&d<2?(console.log(`[Auth] Retrying session check (attempt ${d}/2)`),s("retry_check_session",{retryCount:d}),setTimeout(()=>{h=!1,j()},500)):(console.log("[Auth] Auth failed, loading=false will trigger page-level redirect"),s("auth_failed_no_retry",{path:r,globalRetryCount:d,allowRetry:e}))}},D=async(e,r)=>{if(!T.current)return!1;d=0,v(!0),S(null),u();let t=Date.now();s("sign_in_start",{email:e.substring(0,3)+"***"}),console.log("[Debug] Attempting to sign in with email:",e),g.recordEvent("login_flow_start",{email:e.substring(0,3)+"***",timestamp:Date.now()});try{let o=T.current;console.log("[Debug] Calling supabase.auth.signInWithPassword"),s("supabase_auth_start");let{data:n,error:a}=await o.auth.signInWithPassword({email:e,password:r});if(a)return console.error("[Debug] Error signing in:",a),s("supabase_auth_error",{error:a.message}),S(a.message),l({error:a.message,stage:"supabase_auth"}),fetch("/api/monitoring/auth-failure",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:e,reason:a.message})}).catch(()=>{}),!1;if(!n.session)return console.error("[Debug] No session returned after sign in"),s("no_session_returned"),S("Authentication failed. Please try again."),l({error:"No session returned",stage:"supabase_auth"}),!1;console.log("[Debug] Sign-in successful, user:",n.user.id),console.log("[Debug] Session token available:",!!n.session.access_token),s("supabase_auth_success",{userId:n.user.id,hasSession:!!n.session}),g.recordEvent("login_supabase_success",{user_id:n.user.id,has_session:!!n.session,timestamp:Date.now()});let i=()=>{fetch("/api/monitoring/auth-success",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include"}).catch(()=>{})};"requestIdleCallback"in window?window.requestIdleCallback(i,{timeout:1e3}):i();try{console.log("[Debug] Fetching user data after sign-in..."),s("fetch_user_after_signin_start");let e=await fetch("/api/auth/user",{headers:{Authorization:`Bearer ${n.session.access_token}`}});if(console.log("[Debug] API response status:",e.status),!e.ok)throw s("api_error",{status:e.status}),Error(`API error: ${e.status}`);let r=await e.json();if(console.log("[Debug] User data from API:",r),!r.user)throw s("no_user_data"),Error("No user data returned from API");s("user_data_fetched",{hasOrg:!!r.organization}),c(r.user),O(!0),r.organization&&I(r.organization),o.auth.onAuthStateChange((e,r)=>{"SIGNED_OUT"===e?A():"TOKEN_REFRESHED"===e&&r&&console.log("[Debug] Session token refreshed during sign in")}),console.log("[Debug] Successfully signed in and loaded user data");let a=Date.now()-t;return s("redirect_to_loading",{total_duration_ms:a}),g.recordEvent("login_complete_success",{user_id:r.user.user_id,duration_ms:a,has_organization:!!r.organization}),u(),P.push("/loading"),!0}catch(e){return console.error("[Debug] Error fetching user data after sign-in:",e),s("signin_api_error",{error:e instanceof Error?e.message:"unknown"}),l({error:e instanceof Error?e.message:"unknown",stage:"fetch_user_after_signin"}),await o.auth.signOut(),S("Failed to load user profile. Please try again."),!1}}catch(e){return console.error("[Debug] Unexpected error in signIn:",e),s("unexpected_error",{error:e instanceof Error?e.message:"unknown"}),l({error:e instanceof Error?e.message:"unknown",stage:"signin"}),S("An unexpected error occurred. Please try again."),!1}finally{v(!1)}},C=async(e,r,t,o,n)=>{if(v(!0),S(null),console.log("[Debug] Attempting to sign up with email:",e),console.log("[Debug] First Name:",t,"Last Name:",n),console.log("[Debug] Organization Name:",o),!o)return console.error("[Debug] Organization name is required"),S("Organization name is required for signup"),v(!1),!1;
1try{console.log("[Debug] Calling enhanced signup API endpoint");let a=await fetch("/api/auth/signup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r,firstName:t,lastName:n,orgName:o})}),i=await a.json();if(!a.ok)return console.error("[Debug] Signup API error:",i),S(i.error||"Failed to create account. Please try again."),v(!1),!1;return console.log("[Debug] Signup successful:",i),v(!1),!0}catch(e){return console.error("[Debug] Exception during signup:",e),S("An unexpected error occurred. Please try again."),v(!1),!1}},x=async()=>{if(T.current)try{v(!0),S(null),I(null);let e=T.current,{error:r}=await e.auth.signOut();if(r){console.error("Error signing out:",r),S(r.message);return}c(null),O(!1),localStorage.removeItem("supabase.auth.token"),window.location.href="/login"}catch(e){console.error("Unexpected error signing out:",e),S("An unexpected error occurred")}finally{v(!1)}};return(0,r.jsx)(b.Provider,{value:{currentUser:i,loading:_,error:w,signIn:D,signOut:x,signUp:C,isAuthenticated:E},children:e})},"useAuth",0,function(){let e=(0,t.useContext)(b);if(void 0===e)throw Error("useAuth must be used within an AuthProvider");return e}],894746)}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.