1import{j as e}from"./data-DN-eP4ae.js";import{r as n,e as gs,h as Es,N as As}from"./react-BUOzgyp0.js";import{B as rs}from"./BrandLogo-DSytlRZz.js";import{ji as Ae,aK as Is,C as Ps,B as C,bA as $,s as o,aH as Y,n as G,cs as zs,U as qs,y as Bs,jj as Re,jk as Gs,jl as Ls,jm as Ee,aF as as,E as ns,G as is,H as os,jn as Ys,V as Ms,bu as W,av as ye,o as Fs,l as Ds,jo as ls,jp as cs,jq as Ws}from"./index-6GUxm5Tl.js";import{C as J,b as V,c as H,d as Z,a as X}from"./card-Bpoa90g8.js";import{R as $s,a as Us}from"./radio-group-CORZjgwn.js";import{e as Ks,I as Js,l as Vs,t as ds}from"./useWorkProfiles-D9NYSjhH.js";import{u as Hs}from"./useIndustryTaxonomy-w6mlpeyU.js";import"./onboarding-business-types-InVCPvhM.js";import{i as Zs}from"./registry-BuwsUV1m.js";import{O as Xs}from"./OutcomeChooser-DBg_DoAG.js";import{b as Qs}from"./business-type-defaults-CZCTHSrA.js";import{b as et}from"./invitations-DzA4_zT8.js";import{R as st}from"./rocket-DDgcO4_x.js";import{G as tt}from"./globe-C22yugrV.js";import"./documents-Bju1cS7G.js";import"./charts-BjVT6r80.js";import"./index-DuA5XNr_.js";import"./business-taxonomy-DjKP5GVb.js";import"./wheat-oebZg5ML.js";import"./factory-CrfF_Yvt.js";import"./radio-BSNd35KV.js";import"./party-popper-CCyO5Xb5.js";import"./scale-Ch_1J_wC.js";import"./utensils-crossed-BnBX42KK.js";import"./repeat-DtLx7W2-.js";import"./message-circle-BaAVvJru.js";import"./badge-dollar-sign-DDsaUsAf.js";function rt({orgId:a,businessTypeLabel:h,industry:g}){const[t,r]=n.useState(!1),[q,ie]=n.useState(!1),T=n.useMemo(()=>{const b=Qs(g,h);return Ae.filter(j=>!j.core&&b.suggestedModules.includes(j.key))},[g,h]);if(!a||T.length===0)return null;const k=async()=>{r(!0);try{const{data:b}=await o.from("org_settings").select("setting_value").eq("org_id",a).eq("setting_key","modules").maybeSingle(),O={...(b==null?void 0:b.setting_value)||{}};for(const P of Ae)P.core||T.some(i=>i.key===P.key)?O[P.key]=!0:typeof O[P.key]!="boolean"&&(O[P.key]=!1);const{error:f}=await o.from("org_settings").upsert({org_id:a,setting_key:"modules",setting_value:O,updated_at:new Date().toISOString()},{onConflict:"org_id,setting_key"});if(f)throw f;Y("onboarding_step_completed",{step:"recommended_setup",count:T.length}),ie(!0),G.success("Recommended setup turned on")}catch{G.error("Could not turn this on - you can do it later in Admin Settings.")}finally{r(!1)}};return e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-4 text-left",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Recommended for your business"})]}),e.jsxs("p",{className:"mb-3 text-xs text-muted-foreground",children:[h?"Businesses like yours usually start with these.":"A good place to start."," You can change any of them later."]}),e.jsx("ul",{className:"mb-3 space-y-1.5",children:T.map(b=>e.jsxs("li",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:b.label}),e.jsxs("span",{className:"text-muted-foreground",children:[" - ",b.purpose]})]},b.key))}),q?e.jsxs("p",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Ps,{className:"h-4 w-4 text-primary"})," Turned on"]}):e.jsxs(C,{variant:"outline",size:"sm",onClick:k,disabled:t,children:[t&&e.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),"Turn on"]})]})}function at({orgId:a}){const h=gs(),g=Ks(),t=n.useRef(!1);return n.useEffect(()=>{!a||t.current||(t.current=!0,g.mutate(void 0))},[a]),e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3 text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:"Make it yours"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Two things make this useful today: one customer to work with, and the people who work with you."}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>h("/contacts?new=1"),children:[e.jsx(zs,{className:"mr-2 h-4 w-4"}),"Add first customer"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>h("/admin-panel?section=team"),children:[e.jsx(qs,{className:"mr-2 h-4 w-4"}),"Invite your team"]})]})]})}const me={step:1,orgName:"",businessTypeKey:"",businessTypeOther:"",website:"",businessPhone:"",teamSize:"",customerType:"",primaryOutcome:null,outcomes:[],orgId:null,updatedAt:0},nt="ducecrm_onboarding_draft:",it=1e3*60*60*24*14;function _e(a){return`${nt}${a}`}function Ie(a){if(!a||typeof window>"u")return{...me};try{const h=window.localStorage.getItem(_e(a));if(!h)return{...me};const g=JSON.parse(h);return g.updatedAt&&Date.now()-g.updatedAt>it?(window.localStorage.removeItem(_e(a)),{...me}):{...me,...g}}catch{return{...me}}}function ot(a,h){if(!(!a||typeof window>"u"))try{const t={...Ie(a),...h,updatedAt:Date.now()};window.localStorage.setItem(_e(a),JSON.stringify(t))}catch{}}function us(a){if(!(!a||typeof window>"u"))try{window.localStorage.removeItem(_e(a))}catch{}}function lt(a,h){return a.onboardingStep==="completed"||a.hasGoals||a.onboardingStep==="goals_saved"||a.onboardingStep==="skipped_goals"?3:Math.max(2,Math.min(h,3))}async function ct(a,h){const g=[],t=(i,y,R,Q=!0)=>g.push({key:i,label:y,met:R,blocking:Q});if(!a||!h){t("organisation","Your business",!1),t("membership","Your access to the business",!1);const i=g.filter(y=>y.blocking&&!y.met);return{ready:!1,requirements:g,missing:i}}let r=null,q=!1;try{const{data:i,error:y}=await o.from("organisations").select("id, name, settings").eq("id",a).maybeSingle();if(y)throw y;q=!!(i!=null&&i.id),r=(i==null?void 0:i.settings)||{}}catch{q=!1}t("organisation","Your business",q);const ie=!!(r!=null&&r.industry&&(r!=null&&r.industry_code)&&(r!=null&&r.industry_category));t("business_setup","What type of business you run",ie);const T=!!(r!=null&&r.primary_outcome||r!=null&&r.primary_goal||r!=null&&r.team_size);t("goals","What you want DuceCRM to help with",T);let k=!1;try{const{data:i,error:y}=await o.from("users").select("id, org_id").eq("auth_id",h).maybeSingle();if(y)throw y;k=(i==null?void 0:i.org_id)===a}catch{k=!1}t("membership","Your access to the business",k);let b=!1;try{const{data:i,error:y}=await o.from("org_business_intel").select("org_id, business_types").eq("org_id",a).maybeSingle();if(y)throw y;b=!!(i!=null&&i.org_id)}catch{b=!1}t("business_intelligence","Your business details",b);let j=!1;try{const{data:i,error:y}=await o.from("org_settings").select("setting_key").eq("org_id",a).in("setting_key",["modules","guided_success"]);if(y)throw y;j=Array.isArray(i)&&i.length>0}catch{j=!1}t("workspace_settings","Your workspace setup",j);let O=!0;try{const{data:i}=await o.from("ai_credit_wallets").select("org_id").eq("org_id",a).maybeSingle();O=!!(i!=null&&i.org_id)}catch{O=!0}t("ai_allowance","Your AI starter credits",O,!1);let f=!1;try{const{data:i,error:y}=await o.rpc("resolve_active_org");if(y)throw y;
1const R=Array.isArray(i)?i[0]:i,Q=typeof R=="string"?R:(R==null?void 0:R.org_id)??(R==null?void 0:R.id)??null;f=Q?Q===a:k}catch{f=k}t("dashboard_resolves","Your workspace access",f);const P=g.filter(i=>i.blocking&&!i.met);return{ready:P.length===0,requirements:g,missing:P}}function ms(a){const h=a.trim();return h?/^https?:\/\//i.test(h)?h:`https://${h}`:""}const dt=[{value:"just_me",label:"Just me"},{value:"2-5",label:"2â5"},{value:"6-15",label:"6â15"},{value:"16-50",label:"16â50"},{value:"50+",label:"50+"}],ut=[{value:"b2c",label:"People"},{value:"b2b",label:"Businesses"},{value:"both",label:"Both"}];function Ft(){const a=gs(),[h]=Es(),g=h.get("mode")==="new",{user:t,profile:r,isLoading:q,noActiveOrg:ie,refreshProfile:T}=Bs(),[k,b]=n.useState(1),[j,O]=n.useState(""),[f,P]=n.useState(""),[i,y]=n.useState(""),[R,Q]=n.useState(null),[ge,fs]=n.useState(null),[be,hs]=n.useState(null),{industries:mt,nameOf:Pe,groupOf:ps}=Hs(),xs={primary:f||null,subType:R,customName:i,customGroup:ge,customClosest:be},ys=s=>{P(s.primary??""),Q(s.subType),y(s.customName),fs(s.customGroup),hs(s.customClosest??null)},je=()=>Vs({industrySlug:f||null,industryName:Pe(f),industryGroupSlug:f?ps(f):ge,customName:i}),_s=!!f||i.trim().length>1,[oe,ze]=n.useState(""),[ee,qe]=n.useState(""),[se,U]=n.useState(!1),[w,we]=n.useState(null),[bs,le]=n.useState(!1),[z,js]=n.useState(()=>(h.get("ref")||Re()||"").toUpperCase()),[E,Be]=n.useState(null),[Ge,ve]=n.useState(!1);n.useEffect(()=>{const s=z.trim();if(!s){Be(null),ve(!1);return}Gs(s);let l=!1;ve(!0);const c=setTimeout(async()=>{const d=await Ls(s);l||(Be(d),ve(!1))},450);return()=>{l=!0,clearTimeout(c)}},[z]);const Le=n.useRef(null);n.useEffect(()=>{const s=z.trim();if(!s||!(t!=null&&t.email)||!(E!=null&&E.valid))return;const l=`${s}:${t.id}`;Le.current!==l&&(Le.current=l,(async()=>{try{await Ee({referralCode:s,email:t.email,companyName:j||(r==null?void 0:r.full_name)||t.email,userId:t.id,monthlyRevenue:0,usersCount:1,metadata:{stage:"onboarding_initiated"}})}catch(c){console.warn("[onboarding] Early partner referral capture non-blocking warning:",c)}})())},[z,t==null?void 0:t.id,t==null?void 0:t.email,E==null?void 0:E.valid,j,r==null?void 0:r.full_name]);const[M,Ne]=n.useState(""),[te,Ye]=n.useState(""),[ws,gt]=n.useState(""),[B,ce]=n.useState([]),re=B[0]??null,[ke,Me]=n.useState(!1),[vs,fe]=n.useState(!1),[Fe,De]=n.useState(!1),[Se,Ce]=n.useState([]),Te=n.useRef(!1),We=n.useRef(!1),$e=n.useRef(!1),D="pending_invite_token",Ue=h.get("invite_token"),[Ke,Ns]=n.useState(!1),[v,Oe]=n.useState(()=>g?null:Ue||localStorage.getItem(D)),A=!!v,[u,he]=n.useState(null),[ks,de]=n.useState(()=>!!v),[Je,Ve]=n.useState(!1),[Ss,He]=n.useState(!1),[Cs,K]=n.useState(()=>!(Ue||localStorage.getItem(D)));if(n.useEffect(()=>{if(!v){de(!1);return}let s=!1;return de(!0),(async()=>{try{const{data:c,error:d}=await o.rpc("get_invite_token_info",{p_token:v});if(d)throw d;const m=Array.isArray(c)?c[0]:c;if(m&&m.org_name&&!m.is_expired&&!m.is_used){if(s)return;he({valid:!0,org_name:m.org_name,logo_url:m.logo_url,role:m.role,email:m.email}),de(!1);return}if(s)return;localStorage.getItem(D)===v&&localStorage.removeItem(D),he(null),Oe(null),de(!1),a(r!=null&&r.org_id?"/dashboard":"/onboarding",{replace:!0})}catch{s||de(!1)}})(),()=>{s=!0}},[v,a,r==null?void 0:r.org_id]),n.useEffect(()=>{if(q)return;if(g){K(!1);return}if(v){K(!1);return}if(Ke){K(!1);return}if(!t){K(!1);return}if(r&&r.org_id){K(!1);return}let s=!1;return K(!0),(async()=>{const l=async()=>{const{data:c,error:d}=await o.rpc("get_pending_invite_for_current_user");if(d)throw d;return Array.isArray(c)?c[0]:c};try{let c=null;try{c=await l()}catch{try{c=await l()}catch{}}!s&&c&&c.token&&(localStorage.setItem(D,c.token),he({valid:!0,org_name:c.org_name,logo_url:c.logo_url,role:c.role,email:c.email}),Oe(c.token))}finally{s||K(!1)}})(),()=>{s=!0}},[v,t,q,r,Ke,g]),n.useEffect(()=>{var l;if(!(t!=null&&t.id)||A||Te.current)return;Te.current=!0;const s=Ie(t.id);s.orgName&&O(s.orgName),s.businessTypeKey&&P(s.businessTypeKey),s.businessTypeOther&&y(s.businessTypeOther),s.website&&ze(s.website),s.businessPhone&&qe(s.businessPhone),s.teamSize&&Ne(s.teamSize),s.customerType&&Ye(s.customerType),(l=s.outcomes)!=null&&l.length?ce(s.outcomes):s.primaryOutcome&&ce([s.primaryOutcome]),s.orgId&&we(s.orgId),s.updatedAt?Y("onboarding_resumed",{step:s.step}):$e.current||($e.current=!0,Y("onboarding_started",{mode:g?"additional":"first"}))},[t==null?void 0:t.id,A,g]),n.useEffect(()=>{!Te.current||!(t!=null&&t.id)||A||ot(t.id,{step:k,orgName:j,businessTypeKey:f,businessTypeOther:i,website:oe,businessPhone:ee,teamSize:M,customerType:te,primaryOutcome:re,outcomes:B,orgId:w})},[t==null?void 0:t.id,A,k,j,f,i,oe,ee,M,te,re,B,w]),n.useEffect(()=>{if(!(t!=null&&t.id)||A)return;const s=()=>{k<3&&Y("onboarding_abandoned",{step:k})};return window.addEventListener("beforeunload",s),()=>window.removeEventListener("beforeunload",s)},[t==null?void 0:t.id,A,k]),n.useEffect(()=>{if(q||!(t!=null&&t.id)||A||g||We.current)return;const s=Ie(t.id),l=s.orgId||(r==null?void 0:r.org_id)||null;if(!l)return;We.current=!0;let c=!1;return(async()=>{try{const[{data:d},{data:m}]=await Promise.all([o.from("users").select("onboarding_step").eq("auth_id",t.id).maybeSingle(),o.from("organisations").select("name, settings").eq("id",l).maybeSingle()]);if(c)return;const p=(m==null?void 0:m.settings)||{},S=(d==null?void 0:d.onboarding_step)??null;if(!["org_created","goals_saved","skipped_goals"].includes(S||"")&&!s.orgId)return;if(S==="completed"||S==="invite_joined"){us(t.id);return}if(m!=null&&m.name&&!j&&O(m.name),p.team_size&&!M&&Ne(p.team_size),B.length===0){const N=Array.isArray(p.goals)?p.goals:[];N.length?ce(N):p.primary_outcome&&ce([p.primary_outcome])}we(l),fe(!0),b(lt({onboardingStep:S,hasOrg:!0,hasGoals:!!(p.primary_outcome||p.primary_goal||p.team_size)},s.step||2))}catch{}})(),()=>{c=!0}},[q,t==null?void 0:t.id,A,g,r==null?void 0:r.org_id,j,M,B.length]),q||ks||Cs||t&&!r&&!v)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx($,{className:"h-8 w-8 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs(J,{className:"w-full max-w-md text-center",children:[e.jsxs(V,{children:[e.jsx(rs,{className:"h-8 mb-2 mx-auto object-contain"}),e.jsx(H,{className:"text-page-title",children:"Sign In Required"}),e.jsx(Z,{children:"Please sign in to continue setting up your account."})]}),e.jsx(X,{children:e.jsx(C,{onClick:()=>
1a("/auth?mode=login"),className:"w-full",size:"lg",children:"Go to Sign In"})})]})});if(r!=null&&r.org_id&&!v&&!g&&!vs)return e.jsx(As,{to:"/dashboard",replace:!0});const Ts=async()=>{var s,l;if(!(!t||!v)){Ve(!0),He(!1);try{const d=(await o.auth.getSession()).data.session,m=((s=d==null?void 0:d.user.user_metadata)==null?void 0:s.full_name)||((l=d==null?void 0:d.user.user_metadata)==null?void 0:l.name)||"",p=(u==null?void 0:u.org_name)||"";if(m.trim())try{const{error:x}=await o.functions.invoke("update-user-name",{body:{full_name:m}});x&&console.warn("update-user-name failed (non-fatal):",x)}catch(x){console.warn("update-user-name threw (non-fatal):",x)}await et(v),await o.from("users").update({onboarding_step:"invite_joined"}).eq("auth_id",t.id),await T();let S=p;const{data:_}=await o.from("users").select("org_id, full_name").eq("auth_id",t.id).single();if(_!=null&&_.org_id){const{data:x}=await o.from("organisations").select("name").eq("id",_.org_id).single();x!=null&&x.name&&(S=x.name,O(x.name))}try{await o.functions.invoke("send-join-confirmation-email",{body:{orgName:S,fullName:(_==null?void 0:_.full_name)||m}})}catch(x){console.warn("send-join-confirmation-email failed (non-fatal):",x)}const N=(z==null?void 0:z.trim())||Re();if(N)try{const x=await Ee({referralCode:N,email:t.email||"",companyName:S||"Joined Business",externalId:(_==null?void 0:_.org_id)||null,userId:t.id,monthlyRevenue:0,usersCount:1,metadata:{join_type:"invite_joined",invite_token:v,org_id:_==null?void 0:_.org_id,org_name:S}});x.success?(console.log("[onboarding] Partner referral captured on invite join:",x),ls()):console.warn("[onboarding] Partner referral registration warning on invite join:",x.error)}catch(x){console.warn("[onboarding] Partner referral dispatch error on invite join:",x)}localStorage.removeItem(D),cs(t.id,_==null?void 0:_.org_id),G.success(`Welcome to ${S||"your team"}!`),a("/")}catch(c){const d=(c==null?void 0:c.message)||"Failed to join team";if(d.toLowerCase().includes("different email address")){He(!0);return}G.error(d)}finally{Ve(!1)}}},Os=async s=>{if(s.preventDefault(),!t){G.error("You must be signed in to create a business."),a("/auth");return}if(!_s){G.error("Choose the kind of business you run, or tell us in your own words.");return}if(w){fe(!0),b(2);return}U(!0);try{const{data:l,error:c}=await o.auth.getSession();if(c||!l.session){G.error("Your sign-in session has expired. Please sign in again."),a("/auth?mode=login");return}const{data:d,error:m}=await o.auth.getUser(),p=d.user;if(m||!p){G.error("Your sign-in session could not be verified. Please sign in again."),await o.auth.signOut(),a("/auth?mode=login");return}const S=Intl.DateTimeFormat().resolvedOptions().timeZone,_=ms(oe),N=je(),x={...ds(N),timezone:S,website:_,business_phone:ee},{data:ae,error:Qe}=await o.rpc("create_org_for_current_user",{org_name:j,org_settings:x});if(Qe)throw Qe;if(!ae)throw new Error("Organisation creation returned no ID");const L=ae;we(L);const{error:es}=await o.rpc("save_business_industries",{p_org_id:L,p_primary_industry:f||null,p_sub_type:R,p_secondary_industries:[],p_custom_industry_name:f?null:i.trim()||null,p_custom_industry_category:f?null:ge,p_source:"onboarding",p_custom_closest_industry:f?null:be,p_review_required:!f&&!!i.trim()});es&&console.warn("[onboarding] could not save industry:",es.message);const{data:ss}=await o.from("pipelines").insert({name:"Default Pipeline",org_id:L,is_default:!0}).select("id").single();if(ss){const I=Zs(N.pipelineKey||"general");await o.from("pipeline_stages").insert(I.map(ne=>({name:ne.name,key:ne.key,position:ne.position,probability:ne.probability,color:ne.color,is_default_start:ne.is_default_start||!1,pipeline_id:ss.id,org_id:L})))}const{error:Rs}=await o.from("org_business_intel").upsert({org_id:L,business_types:N.taxonomyKeys,service_models:[],custom_type:N.customType,customer_type:te||null,updated_by:p.id},{onConflict:"org_id"});Rs&&Y("onboarding_write_failed",{record:"org_business_intel"});const ts=(z==null?void 0:z.trim())||Re();if(ts)try{const I=await Ee({referralCode:ts,email:p.email||"",companyName:j,externalId:L,userId:p.id,phone:ee,website:_,monthlyRevenue:0,usersCount:1,metadata:{industry:N.industry,business_type:N.businessTypeLabel}});I.success?(console.log("[onboarding] Partner referral registered on PartnerHub:",I),ls()):console.warn("[onboarding] Partner referral registration warning:",I.error)}catch(I){console.warn("[onboarding] Partner referral dispatch error:",I)}await o.from("users").update({onboarding_step:"org_created"}).eq("auth_id",p.id),console.log("[onboarding] org created, refreshing profile...",L),fe(!0),await T();const{data:F}=await o.from("users").select("org_id").eq("auth_id",p.id).single();if(console.log("[onboarding] post-refresh org_id:",F==null?void 0:F.org_id),g&&(F==null?void 0:F.org_id)!==L)await o.rpc("switch_active_org",{_org_id:L}),await T();else if(!(F!=null&&F.org_id)){console.log("[onboarding] org_id missing, attempting switch_active_org..."),await o.rpc("switch_active_org",{_org_id:L}),await T();const{data:I}=await o.from("users").select("org_id").eq("auth_id",p.id).single();if(console.log("[onboarding] post-switch org_id:",I==null?void 0:I.org_id),!(I!=null&&I.org_id)){le(!0),U(!1);return}}le(!1),Y("onboarding_step_completed",{step:"business_setup",industry_id:N.industryId,business_type:N.industryCode,custom:f==="other"}),b(2)}catch(l){const c=(l==null?void 0:l.message)||"Failed to create business";/sign(ed)? in|session|JWT|auth/i.test(c)?(G.error("Please sign in again before creating your business."),a("/auth?mode=login")):G.error(c)}finally{U(!1)}},Ze=async s=>{if(!w){b(3);return}Me(!0);try{const{data:l}=await o.from("organisations").select("settings").eq("id",w).single(),c=(l==null?void 0:l.settings)||{},d=Intl.DateTimeFormat().resolvedOptions().timeZone,m=je(),{error:p}=await o.from("organisations").update({settings:{...c,...ds(m),timezone:d,website:ms(oe),business_phone:ee,team_size:M,primary_goal:ws,primary_outcome:re,goals:B}}).eq("id",w);if(p)throw p;await o.rpc("save_business_industries",{p_org_id:w,p_primary_industry:f||null,p_sub_type:R,p_secondary_industries:[],p_custom_industry_name:f?null:i.trim()||null,p_custom_industry_category:f?null:ge,p_source:"onboarding",p_custom_closest_industry:f?null:be,p_review_required:!f&&!!i.trim()});const{error:S}=await o.from("org_business_intel").upsert({org_id:w,business_types:m.taxonomyKeys,service_models:[],custom_type:m.customType,customer_type:te||null},{onConflict:"org_id"});if(S)throw S;const _=new Set(Ws(B)),N={};for(const ae of Ae)N[ae.key]=ae.core?!0:_.has(ae.key);const{error:x}=await o.from("org_settings").upsert([{org_id:w,setting_key:"modules",setting_value:N,updated_at:new Date().toISOString()},{org_id:w,setting_key:"guided_success",setting_value:{outcome:re,goals:B,skipped:[],celebrated:[]},updated_at:new Date().toISOString()}],{onConflict:"org_id,setting_key"});if(x)throw x;t&&await o.from("users").update({onboarding_step:s!=null&&s.skipped?"skipped_goals":"goals_saved"}).eq("auth_id",t.id),Y("onboarding_step_completed",{step:"business_needs",skipped:!!(s!=null&&s.skipped),team_size:M||null,outcome:re}),b(3)}catch{Y("onboarding_write_failed",{step:"business_needs"}),G.error("We could not save that. Check your connection and try again.")}finally{Me(!1)}},ue=(u==null?void 0:u.org_name)||j,pe=u==null?void 0:u.logo_url,Xe=ue?ue.slice(0,2).toUpperCase():"DC",xe=({size:s="h-14 w-14"})=>pe?e.jsxs(ns,{className:`${s} mb-2`,children:[e.jsx(is,{src:pe,alt:ue}),e.jsx(os,{className:"text-lg font-bold bg-primary text-primary-foreground",children:Xe})]}):e.jsx(rs,{className:"h-8 mb-2 object-contain"});if(bs&&w){const s=async()=>{U(!0),le(!1);try{await o.rpc("switch_active_org",{_org_id:w}),await T();const{data:l}=await o.from("users").select("org_id").eq("auth_id",t.id).single();l!=null&&l.org_id?b(2):le(!0)}catch{le(!0)}finally{U(!1)}};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(J,{className:"w-full max-w-lg text-center",children:[e.jsxs(V,{children:[e.jsx("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-lg bg-amber-100 dar
1k:bg-amber-900/30",children:e.jsx(as,{className:"h-8 w-8 text-amber-600 dark:text-amber-400"})}),e.jsx(H,{className:"text-page-title",children:"Almost There"}),e.jsx(Z,{className:"text-base",children:"We created your business, but we're still finalizing your workspace access. This usually resolves in a moment."})]}),e.jsx(X,{children:e.jsxs(C,{onClick:s,className:"w-full",size:"lg",disabled:se,children:[se&&e.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),"Retry Activation"]})})]})})}if(k===3){const s=je(),l=s.businessTypeLabel,c=async()=>{U(!0),De(!0),Ce([]);try{ie&&w&&(await o.rpc("switch_active_org",{_org_id:w}),await T());const d=await ct(w,(t==null?void 0:t.id)??null);if(!d.ready){Ce(d.missing),Y("onboarding_write_failed",{step:"completion",missing:d.missing.map(m=>m.key)});return}t&&await o.from("users").update({onboarding_step:"completed"}).eq("auth_id",t.id),await T(),us(t==null?void 0:t.id),fe(!1),Y("onboarding_completed",{business_type:s.industryCode,team_size:M||null,outcome:re}),cs(t==null?void 0:t.id,w),a("/dashboard",{replace:!0})}catch{Ce([{key:"dashboard_resolves",label:"Your workspace access",met:!1,blocking:!0}])}finally{De(!1),U(!1)}};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(J,{className:"w-full max-w-lg text-center",children:[e.jsxs(V,{children:[e.jsx("div",{className:"mx-auto mb-4 flex flex-col items-center",children:A&&pe?e.jsxs(ns,{className:"h-16 w-16 mb-2",children:[e.jsx(is,{src:pe,alt:ue}),e.jsx(os,{className:"text-xl font-bold bg-primary/10 text-primary",children:Xe})]}):e.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(st,{className:"h-8 w-8 text-primary"})})}),e.jsx(H,{className:"text-page-title",children:"You're All Set!"}),e.jsx(Z,{className:"text-base",children:A?e.jsxs(e.Fragment,{children:["Welcome to ",e.jsx("span",{className:"font-semibold text-foreground",children:ue}),". You've joined the team!"]}):e.jsxs(e.Fragment,{children:["Your workspace is ready for your"," ",e.jsx("span",{className:"font-semibold text-foreground",children:l||j}),l?" business":"","."]})})]}),e.jsxs(X,{className:"space-y-4",children:[!A&&e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3 text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:"How DuceCRM works"}),e.jsxs("ul",{className:"mt-2 space-y-1.5 text-xs text-muted-foreground",children:[e.jsx("li",{children:"Keep every customer in one place, however they reach you."}),e.jsx("li",{children:"Sell from your products and services - offer, invoice, payment."}),e.jsx("li",{children:"DuceCRM tells you who needs attention, so nothing is forgotten."})]}),B.length>0&&e.jsxs("p",{className:"mt-2.5 text-xs text-muted-foreground",children:["Set up for: ",B.map(d=>Ys[d]).filter(Boolean).join(", "),". Everything else stays one switch away in Settings."]})]}),!A&&e.jsx(at,{orgId:w}),!A&&e.jsx(rt,{orgId:w,businessTypeLabel:l,industry:s.industry}),Se.length>0&&e.jsxs("div",{className:"rounded-lg border border-amber-300 bg-amber-50 p-3 text-left dark:border-amber-900/50 dark:bg-amber-900/20",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ms,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"}),"We're still finishing your workspace"]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Nothing you entered is lost. These parts still need to save:"}),e.jsx("ul",{className:"mt-2 list-disc pl-5 text-xs text-muted-foreground",children:Se.map(d=>e.jsx("li",{children:d.label},d.key))})]}),e.jsxs(C,{onClick:c,className:"w-full",size:"lg",disabled:se||Fe,children:[(se||Fe)&&e.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),Se.length>0?"Try again":"Go to Dashboard"]})]})]})})}if(k===2)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(J,{className:"w-full max-w-lg",children:[e.jsxs(V,{className:"text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex flex-col items-center",children:e.jsx(xe,{})}),e.jsx(H,{className:"text-page-title",children:"A Little About Your Business"}),e.jsx(Z,{children:"This helps us set up DuceCRM for your business"})]}),e.jsxs(X,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border bg-muted/40 px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Type of business"}),e.jsx("p",{className:"truncate text-sm font-medium",children:f==="other"?i.trim()||"Other":Pe(f)||"Not set"})]}),e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>b(1),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{children:"How big is your team?"}),e.jsx($s,{value:M,onValueChange:Ne,className:"grid grid-cols-5 ga
1p-2",children:dt.map(s=>e.jsxs(W,{htmlFor:`ts-${s.value}`,className:`flex items-center justify-center rounded-lg border px-3 py-2.5 text-sm font-medium cursor-pointer transition-colors ${M===s.value?"border-primary bg-primary/10 text-primary":"border-border hover:border-muted-foreground/40"}`,children:[e.jsx(Us,{value:s.value,id:`ts-${s.value}`,className:"sr-only"}),s.label]},s.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(W,{children:["Who do you sell to? ",e.jsx("span",{className:"text-muted-foreground text-xs font-normal",children:"(optional)"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:ut.map(s=>e.jsx("button",{type:"button",onClick:()=>Ye(te===s.value?"":s.value),className:`rounded-lg border px-3 py-2.5 text-sm font-medium transition-colors ${te===s.value?"border-primary bg-primary/10 text-primary":"border-border hover:border-muted-foreground/40"}`,children:s.label},s.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{children:"What would you like DuceCRM to help with?"}),e.jsx(Xs,{bare:!0,multi:!0,values:B,onToggle:ce})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsx(C,{variant:"outline",className:"flex-1",disabled:ke,onClick:()=>Ze({skipped:!0}),children:"Skip"}),e.jsxs(C,{className:"flex-1",size:"lg",onClick:()=>Ze(),disabled:ke,children:[ke&&e.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),"Continue"]})]})]})]})});if(A){const s=((u==null?void 0:u.email)||"").toLowerCase().trim(),l=((t==null?void 0:t.email)||"").toLowerCase().trim(),c=!!(s&&l&&s!==l),d=Ss||c,m=async()=>{v&&localStorage.setItem(D,v);try{await o.auth.signOut()}catch{}const p=u!=null&&u.email?`/auth?mode=login&invite_token=${v}&email=${encodeURIComponent(u.email)}`:`/auth?mode=login&invite_token=${v}`;a(p)};return d?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(J,{className:"w-full max-w-lg text-center",children:[e.jsxs(V,{children:[e.jsx("div",{className:"mx-auto mb-4 flex flex-col items-center",children:e.jsx(xe,{})}),e.jsx(H,{className:"text-page-title",children:"Wrong Account"}),e.jsx(Z,{children:u!=null&&u.email&&c?e.jsxs(e.Fragment,{children:["You're signed in as"," ",e.jsx("span",{className:"font-semibold text-foreground break-all",children:t.email}),", but this invite was sent to"," ",e.jsx("span",{className:"font-semibold text-foreground break-all",children:u.email}),"."]}):"This invite belongs to a different signed-in account. Sign out, then continue with the invited email address."})]}),e.jsxs(X,{className:"space-y-2",children:[e.jsx(C,{onClick:m,className:"w-full",size:"lg",children:"Sign out and continue"}),e.jsx(C,{variant:"outline",onClick:()=>a("/"),className:"w-full",children:"Cancel"})]})]})}):e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(J,{className:"w-full max-w-lg text-center",children:[e.jsxs(V,{children:[e.jsx("div",{className:"mx-auto mb-4 flex flex-col items-center",children:e.jsx(xe,{})}),e.jsx(H,{className:"text-page-title",children:u!=null&&u.org_name?`Join ${u.org_name}`:"Join Team"}),e.jsx(Z,{children:u!=null&&u.org_name?e.jsxs(e.Fragment,{children:["You've been invited to join ",e.jsx("span",{className:"font-semibold text-foreground",children:u.org_name}),u.role&&e.jsxs(e.Fragment,{children:[" as a ",e.jsx("span",{className:"font-semibold text-primary",children:u.role})]})]}):"You've been invited to join a team"})]}),e.jsxs(X,{className:"space-y-3",children:[e.jsxs(C,{onClick:Ts,className:"w-full",size:"lg",disabled:Je,children:[Je&&e.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),u!=null&&u.org_name?`Join ${u.org_name}`:"Join Team"]}),e.jsx("div",{className:"pt-2 text-center",children:e.jsx(C,{type:"button",variant:"ghost",size:"sm",onClick:()=>{Ns(!0),he(null),Oe(null),localStorage.removeItem(D)},className:"text-xs text-muted-foreground hover:text-foreground",children:"Or set up your own business instead"})})]})]})})}return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(J,{className:"w-full max-w-lg",children:[e.jsxs(V,{className:"text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex flex-col items-center",children:e.jsx(xe,{})}),e.jsx(H,{className:"text-page-title",children:g?"Add a New Business":"Set Up Your Business"}),e.jsx(Z,{children:g?"Create another business - you can switch between businesses any time":"Create your business to get started with DuceCRM"})]}),e.jsx(X,{children:e.jsxs("form",{onSubmit:Os,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(W,{htmlFor:"orgName",children:"Business N
1ame"}),e.jsxs("div",{className:"relative",children:[e.jsx(as,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{id:"orgName",value:j,onChange:s=>O(s.target.value),placeholder:"Acme Inc.",className:"pl-10",required:!0})]})]}),e.jsx(Js,{value:xs,onChange:ys,onSearchMiss:(s,l)=>{o.rpc("record_industry_search_miss",{p_term:s,p_custom_submitted:!0,p_fallback_group:l})}}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(W,{htmlFor:"website",children:["Business Website ",e.jsx("span",{className:"text-muted-foreground text-xs",children:"(optional)"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(tt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{id:"website",value:oe,onChange:s=>ze(s.target.value),placeholder:"yourcompany.com",className:"pl-10",type:"text"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"We'll add https:// automatically if needed"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(W,{htmlFor:"bizPhone",children:["Business Phone ",e.jsx("span",{className:"text-muted-foreground text-xs",children:"(optional)"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{id:"bizPhone",value:ee,onChange:s=>qe(s.target.value),placeholder:"+234 800 000 0000",className:"pl-10",type:"tel"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{htmlFor:"partnerReferralCode",children:["Partner Referral Code ",e.jsx("span",{className:"text-muted-foreground text-xs",children:"(optional)"})]}),Ge&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx($,{className:"w-3 h-3 animate-spin"})," Verifyingâ¦"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ds,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{id:"partnerReferralCode",value:z,onChange:s=>js(s.target.value.toUpperCase()),placeholder:"e.g. PARTNER10",className:"pl-10 font-mono uppercase tracking-wide",type:"text",maxLength:32})]}),(E==null?void 0:E.valid)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-emerald-600 dark:text-emerald-400 font-medium mt-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 inline-block"}),"Referred by ",E.partnerName,E.partnerType&&e.jsxs("span",{className:"text-muted-foreground capitalize",children:["· ",E.partnerType.replace(/_/g," ")]})]}),E&&!E.valid&&z.trim().length>0&&!Ge&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400 mt-1",children:"No active partner found with this code. You can still proceed with registration."})]}),e.jsxs(C,{type:"submit",className:"w-full",size:"lg",disabled:se,children:[se&&e.jsx($,{className:"mr-2 h-4 w-4 animate-spin"}),"Create Business"]}),g&&e.jsx(C,{type:"button",variant:"ghost",className:"w-full",onClick:()=>a("/dashboard"),children:"Back to workspace"})]})})]})})}export{Ft as default};
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.