"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4114],{97740:(e,o,a)=>{a.d(o,{t:()=>_,Providers:()=>A});var n,i=a(95155),t=a(61584),r=a(12115),s=a(56769),l=a.n(s),d=a(75254),c=a.n(d),g=a(22105),u=a(65407),m=a.n(u),h=a(11094);let v=null!==(n=globalThis.prisma)&&void 0!==n?n:new h.PrismaClient;var f=a(74293),w=a(92662);let z=a(2818).env.JWT_SECRET||"your-secure-secret-key",k="your-app-name";async function O(e){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:900,a=Math.floor(Date.now()/1e3);return await new f.P(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setIssuer(k).setExpirationTime(a+o).sign(new TextEncoder().encode(z))}async function E(e){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2592e3,a=Math.floor(Date.now()/1e3);return await new f.P(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setIssuer(k).setExpirationTime(a+o).sign(new TextEncoder().encode(z))}async function C(e){let{payload:o}=await (0,w.V)(e,new TextEncoder().encode(z),{issuer:k});return o}let p=a(2818).env.GOOGLE_REDIRECT_URI;async function I(e){let o=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:"761746785498-3hq4r0flfueh4qpulm7bd8hra7cml15a.apps.googleusercontent.com",client_secret:"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",redirect_uri:p,grant_type:"authorization_code"})});if(!o.ok)throw Error("Failed to exchange code for tokens");let a=await o.json(),n=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:"Bearer ".concat(a.access_token)}});if(!n.ok)throw Error("Failed to fetch user profile");let i=await n.json(),t={email:i.email,name:i.name};return{accessToken:a.access_token,refreshToken:a.refresh_token,profile:t}}let T={id:"tenantAuthMachine",initial:"unauthenticated",context:{request:void 0,host:void 0,domainOrgId:null,userId:void 0,email:void 0,hashedPassword:void 0,organizations:void 0,activeOrganization:null,accessToken:void 0,refreshToken:void 0,error:void 0,googleCode:void 0,originalHost:void 0},states:{unauthenticated:{on:{CHECK_DOMAIN:{target:"checkingDomain",actions:[(e,o)=>({request:o.data.request,originalHost:o.data.originalHost})]},CHECK_SESSION:{target:"checkingSession",actions:[(e,o)=>({request:o.data.request})]},HANDLE_GOOGLE_CALLBACK:{target:"callbackGoogle",actions:[(e,o)=>({googleCode:o.data.code})]}}},checkingDomain:{invoke:{src:async e=>{if(console.log("\uD83D\uDD28 Checking domain",{ctx:e}),!e.request)throw Error("No request for domain check");let o=e.originalHost||e.request.headers.get("host")||e.request.nextUrl.hostname,a=!o.endsWith("appcolo.com"),n=null;if(a){if(!(n=await v.domain.findFirst({where:{domain:o,verified:!0},include:{organization:!0}})))throw Error("Custom domain not found or not verified")}else{let e=o.split(".")[0];if("appcolo"===e)n=null;else{let o=await v.organization.findFirst({where:{slug:e}});if(!o)throw Error("Subdomain org not found");n={organization:o}}}return{host:o,domainOrg:n?n.organization:null}},onDone:{target:"unauthenticated",actions:[(e,o)=>{let a=o.data;return{host:a.host,domainOrgId:a.domainOrg?a.domainOrg.id:null}}]},onError:{target:"error",actions:[(e,o)=>{var a;return{error:(null==o?void 0:null===(a=o.data)||void 0===a?void 0:a.message)||"Domain check failed"}}]}}},checkingSession:{invoke:{src:async e=>{var o,a;if(!e.request)throw Error("No request provided");let n=null===(o=e.request.cookies.get("myAccessToken"))||void 0===o?void 0:o.value,i=null===(a=e.request.cookies.get("myRefreshToken"))||void 0===a?void 0:a.value;if(!n)throw Error("No session token found");let t=await C(n),r=await v.organizationUser.findMany({where:{userId:t.sub},include:{organization:!0}}),s=null;if(e.domainOrgId&&(s=r.find(o=>o.organization.id===e.domainOrgId)),!s&&r.length>0&&(s=r[0]),e.domainOrgId&&!s)throw Error("User not a member of this domain org");return{userId:t.sub,email:t.email,accessToken:n,refreshToken:i,organizations:r.map(e=>({id:e.organization.id,name:e.organization.name,slug:e.organization.slug,role:e.role,customDomain:e.organization.customDomain||void 0,needsOnboarding:e.organization.needsOnboarding||!1})),activeOrganization:s?{id:s.organization.id,name:s.organization.name,slug:s.organization.slug,role:s.role,customDomain:s.organization.customDomain||void 0,needsOnboarding:s.organization.needsOnboarding||!1}:null}},onDone:{target:"authenticated",actions:[(e,o)=>{let a=o.data;return{userId:a.userId,email:a.email,accessToken:a.accessToken,refreshToken:a.refreshToken,organizations:a.organizations,activeOrganization:a.activeOrganization}}]},onError:{target:"unauthenticated",actions:[(e,o)=>({error:(null==o?void 0:o.data).message||"Session check failed"})]}}},loggingInCredentials:{on:{LOGIN_CREDENTIALS:{target:"loggingInCredentials",actions:[(e,o)=>({email:o.data.email,hashedPassword:o.data.password})]}},invoke:{src:async e=>{var o,a;if(!e.email||!e.hashedPassword)throw Error("Missing email/password");let n=await v.user.findUnique({where:{email:e.email}});if(!n||!n.password)throw Error("User not found");if(!await m().compare(e.hashedPassword,n.password))throw Error("Invalid credentials");let i=await v.organizationUser.findMany({where:{userId:n.id},include:{organization:!0}}),t=null;if(e.domainOrgId&&(t=i.find(o=>o.organization.id===e.domainOrgId)),!t&&i.length>0&&(t=i[0]),e.domainOrgId&&!t)throw Error("Not a member of this domain org");let r=await O({sub:n.id,email:null!==(o=n.email)&&void 0!==o?o:""}),s=await E({sub:n.id,email:null!==(a=n.email)&&void 0!==a?a:""});return{userId:n.id,email:n.email||"",organizations:i.map(e=>({id:e.organization.id,name:e.organization.name,slug:e.organization.slug,role:e.role,customDomain:e.organization.customDomain||void 0,needsOnboarding:e.organization.needsOnboarding||!1})),activeOrganization:t?{id:t.organization.id,name:t.organization.name,slug:t.organization.slug,role:t.role,customDomain:t.organization.customDomain||void 0,needsOnboarding:t.organization.needsOnboarding||!1}:null,accessToken:r,refreshToken:s}},onDone:{target:"authenticated",actions:[(e,o)=>{let a=o.data;return{userId:a.userId,email:a.email,organizations:a.organizations,activeOrganization:a.activeOrganization,accessToken:a.accessToken,refreshToken:a.refreshToken,hashedPassword:void 0}}]},onError:{target:"error",actions:[(e,o)=>{var a;return{error:(null==o?void 0:null===(a=o.data)||void 0===a?void 0:a.message)||"Credential login failed",hashedPassword:void 0}}]}}},loggingInGoogle:{entry:[e=>{console.log("\uD83D\uDFE2 Entered loggingInGoogle state",{context:e})}],on:{HANDLE_GOOGLE_CALLBACK:{target:"callbackGoogle",actions:[(e,o)=>{var a;return console.log("\uD83D\uDD35 Received HANDLE_GOOGLE_CALLBACK event",{event:o,code:null===(a=o.data)||void 0===a?void 0:a.code,currentState:"loggingInGoogle"}),e.googleCode=o.data.code,console.log("\uD83D\uDD35 Updated context with googleCode:",e),e}]}},exit:[e=>{console.log("\uD83D\uDD34 Exiting loggingInGoogle state",{context:e,hasGoogleCode:!!e.googleCode})}]},callbackGoogle:{entry:[e=>{console.log("\uD83D\uDFE2 Entered callbackGoogle state",{context:e,hasGoogleCode:!!e.googleCode})}],invoke:{src:async e=>{if(console.log("⚡ Starting Google callback invoke",{context:e,googleCode:e.googleCode}),!e.googleCode)throw Error("No google code provided");let{accessToken:o,refreshToken:a,profile:n}=await I(e.googleCode),i=await v.user.findUnique({where:{email:n.email}});i||(i=await v.user.create({data:{email:n.email,name:n.name}}));let t=await v.organizationUser.findMany({where:{userId:i.id},include:{organization:!0}}),r=null;if(e.domainOrgId&&(r=t.find(o=>o.organization.id===e.domainOrgId)),!r&&t.length>0&&(r=t[0]),e.domainOrgId&&!r)throw Error("User not a member of this domain org");let s=await O({sub:i.id,email:i.email||""}),l=await E({sub:i.id,email:i.email||""});return{userId:i.id,email:i.email||"",organizations:t.map(e=>({id:e.organization.id,name:e.organization.name,slug:e.organization.slug,role:e.role,customDomain:e.organization.customDomain||void 0,needsOnboarding:e.organization.needsOnboarding||!1})),activeOrganization:r?{id:r.organization.id,name:r.organization.name,slug:r.organization.slug,role:r.role,customDomain:r.organization.customDomain||void 0,needsOnboarding:r.organization.needsOnboarding||!1}:null,accessToken:s,refreshToken:l}},onDone:{target:"authenticated",actions:[(e,o)=>{console.log("✅ Google callback successful",{context:e,event:o});let a=o.data;return{userId:a.userId,email:a.email,organizations:a.organizations,activeOrganization:a.activeOrganization,accessToken:a.accessToken,refreshToken:a.refreshToken}}]},onError:{target:"error",actions:[(e,o)=>{var a;return console.log("❌ Google callback failed",{context:e,error:o.data}),{error:(null==o?void 0:null===(a=o.data)||void 0===a?void 0:a.message)||"Google callback failed"}}]}},exit:[e=>{console.log("\uD83D\uDD34 Exiting callbackGoogle state",{context:e})}]},authenticated:{on:{REFRESH:{target:"unauthenticated",actions:[e=>({accessToken:void 0,refreshToken:void 0})]},LOGOUT:{target:"unauthenticated",actions:[()=>({userId:void 0,email:void 0,organizations:void 0,activeOrganization:null,accessToken:void 0,refreshToken:void 0,error:void 0})]}}},error:{on:{CHECK_DOMAIN:{target:"checkingDomain"},CHECK_SESSION:{target:"checkingSession"},LOGIN_CREDENTIALS:{target:"loggingInCredentials"},LOGIN_GOOGLE:{target:"loggingInGoogle"}}}}};var S=a(51615);let y=(0,r.createContext)({organization:null,organizations:[],isAuthenticated:!1,isLoading:!0,checkSession:()=>{},setActiveOrganization:()=>{},logout:()=>{}});function b(e){let{children:o}=e,[a]=(0,r.useState)(()=>g.nb.create(T)),[n,t]=(0,r.useState)(a.getState()),[s,l]=(0,r.useState)(a.getContext());(0,r.useEffect)(()=>{a.send({type:"CHECK_SESSION",data:{request:new S.NextRequest(window.location.href)}})},[a]);let d=()=>{a.send({type:"CHECK_SESSION",data:{request:new S.NextRequest(window.location.href)}})},c={organization:s.activeOrganization||null,organizations:s.organizations||[],isAuthenticated:"authenticated"===n,isLoading:["checkingSession","checkingDomain"].includes(n),error:s.error,checkSession:d,setActiveOrganization:e=>{document.cookie="activeOrganization=".concat(JSON.stringify(e),"; path=/"),d()},logout:()=>{a.send({type:"LOGOUT",data:{request:new S.NextRequest(window.location.href)}}),document.cookie="myAccessToken=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT",document.cookie="myRefreshToken=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT",document.cookie="activeOrganization=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT"}};return(0,i.jsx)(y.Provider,{value:c,children:o})}var x=a(76046),D=a(21051),G=a(89970);let _=(0,r.createContext)(null);function L(){return(0,i.jsx)("div",{children:"Loading..."})}function A(e){let{children:o,dictionary:a}=e,[n,s]=(0,r.useState)(!1),d=(0,x.usePathname)(),{organization:g}=(0,G.d)();return(0,r.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&"d"===e.key&&(e.preventDefault(),s(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,r.useEffect)(()=>{["/admin","/dashboard"].some(e=>{var o;return null!==(o=null==d?void 0:d.startsWith(e))&&void 0!==o&&o})},[d]),(0,i.jsx)(r.Suspense,{fallback:(0,i.jsx)(L,{}),children:(0,i.jsx)(D.a,{dictionary:a,children:(0,i.jsx)(_.Provider,{value:g,children:(0,i.jsx)(b,{children:(0,i.jsx)(t.e,{children:(0,i.jsx)("div",{className:"".concat(l().variable," ").concat(c().variable),children:o})})})})})})}},61584:(e,o,a)=>{a.d(o,{_:()=>s,e:()=>r});var n=a(95155),i=a(12115);let t=(0,i.createContext)(void 0),r=e=>{let{children:o}=e,[a,r]=(0,i.useState)([]);return(0,n.jsx)(t.Provider,{value:{cart:a,addToCart:e=>{r(o=>[...o,e])},removeFromCart:e=>{r(o=>o.filter(o=>o.id!==e))},clearCart:()=>{r([])},updateQuantity:(e,o)=>{r(a=>a.map(a=>a.id===e?{...a,quantity:Math.max(0,o)}:a))}},children:o})},s=()=>{let e=(0,i.useContext)(t);if(!e)throw Error("useCart must be used within a CartProvider");return e}},21051:(e,o,a)=>{a.d(o,{K:()=>s,a:()=>r});var n=a(95155),i=a(12115);let t=(0,i.createContext)(null);function r(e){let{children:o,dictionary:a}=e;return(0,n.jsx)(t.Provider,{value:a,children:o})}function s(){let e=(0,i.useContext)(t);if(null===e)throw Error("useDictionary must be used within a DictionaryProvider");return e}},89970:(e,o,a)=>{a.d(o,{d:()=>t});var n=a(12115);let i=new Map;function t(){let[e,o]=(0,n.useState)(null),[a,t]=(0,n.useState)(!0),[r,s]=(0,n.useState)(null);return(0,n.useEffect)(()=>{(async()=>{try{t(!0);let e=window.location.host;if(i.has(e)){o(i.get(e)),t(!1);return}let a=await fetch("/api/organization/from-domain?host=".concat(encodeURIComponent(e))),n=(await a.json()).organization||null;i.set(e,n),o(n)}catch(e){console.error("Error detecting domain organization:",e),s(e instanceof Error?e:Error(String(e)))}finally{t(!1)}})()},[]),{organization:e,isLoading:a,error:r}}},64114:(e,o,a)=>{a.d(o,{z:()=>l});var n=a(12115),i=a(97740),t=a(65132),r=a(13697),s=a(89970);function l(){let e=(0,n.useContext)(i.t),[o,a]=(0,n.useState)(null),{organization:l}=(0,s.d)(),d=(0,t.parseCookies)(),c=d.anonymousUUID,g=d.accessToken;(0,n.useEffect)(()=>{if(!d.anonymousUUID){let e=(0,r.A)();(0,t.setCookie)(null,"anonymousUUID",e,{maxAge:31536e3,path:"/",secure:!0,sameSite:"lax"})}},[]),(0,n.useEffect)(()=>{(async()=>{try{let e=await fetch("/api/auth/session"),o=await e.json();l&&(o.user={...o.user,activeOrganization:l}),!o.user.id&&c&&(o.user={uuid:c,activeOrganization:l}),a(o.user),console.log("~~~~~Full Session User Info:",JSON.stringify(o.user,null,2))}catch(e){console.error("Error fetching user info:",e),!g&&c&&l?a({uuid:c,activeOrganization:l}):!g&&c&&a({uuid:c})}})()},[g,c,l]);let u={...o||{},activeOrganization:(null==o?void 0:o.activeOrganization)||e};return{user:u,organizations:u.activeOrganization?[u.activeOrganization]:[],activeOrganization:u.activeOrganization,isAuthenticated:null!=u&&!!u.id,isLoading:!o,anonymousId:c,isAnonymous:!g&&!!c}}}}]); //# sourceMappingURL=4114-1fdc201833bd62e9.js.map