// Capability-first setup. Reuses existing Auth, atomic owner creation and tools.
const workspaceDraftKey=actor=>'bookuno.workspace.draft.v1.'+(actor||'guest');
const workspaceAuthKey='bookuno.workspace.auth-return.v1';
// A tour operator from the Tours page (lib/bookuno-tour-intent.js) starts with Group bookings: places on dated departures.
const workspaceTourIntent=()=>{try{return window.BOOKUNO_TOUR_INTENT?.read?.()||null;}catch{return null;}};
function workspaceBlank(){let timezone='Europe/London';try{timezone=Intl.DateTimeFormat().resolvedOptions().timeZone||timezone;}catch{}return {name:'',email:'',currency:'gbp',timezone,tools:workspaceTourIntent()?['groups']:[]};}
function workspaceDraft(raw){
 if(!raw)return null;try{const d=JSON.parse(raw),f=d.form;if(d.version!==1||![1,2,3].includes(d.step)||!f||Object.keys(f).some(k=>!['name','email','currency','timezone','tools'].includes(k))||['name','email','currency','timezone'].some(k=>typeof f[k]!=='string')||f.name.length>160||f.email.length>254||f.timezone.length>80||!window.BOOKUNO_SETUP.currencies.includes(f.currency)||!Array.isArray(f.tools)||f.tools.some(k=>!window.BOOKUNO_TOOLS.keys.includes(k))||new Set(f.tools).size!==f.tools.length)return null;return d;}catch{return null;}
}
function PageWorkspaceSetup(){
 const [source,setSource]=React.useState({loading:true,user:null,recovery:null,pending:false,error:''}),[form,setForm]=React.useState(workspaceBlank),[step,setStep]=React.useState(1),[revision,setRevision]=React.useState(0),[busy,setBusy]=React.useState(false),[error,setError]=React.useState(''),[warning,setWarning]=React.useState('');
 const scope=React.useRef(null),running=React.useRef(null),heading=React.useRef(null),draftRaw=React.useRef(null);
 React.useEffect(()=>{
  let live=true;const tag={actor:null};scope.current=tag;setBusy(false);setSource({loading:true,user:null,recovery:null,pending:false,error:''});setError('');setWarning('');
  async function load(){try{
   if(!window.navigator?.locks?.request)throw Error('Use a current browser with a secure connection to finish setup safely.');
   const api=window.BOOKUNO_API,session=await api.getSession(),user=session?.user||null;tag.actor=user?.id||null;
   const pending=user?await api.getPendingOnboarding():null,recovery=user&&!pending?await api.getWorkspaceSetupRecovery():null;
   if((await api.getSession())?.user?.id!==(user?.id||undefined))throw Error('Your account changed. Reload to continue.');
   let raw=localStorage.getItem(workspaceDraftKey(user?.id));
   if(user&&!raw&&!recovery){try{const marker=JSON.parse(sessionStorage.getItem(workspaceAuthKey)||'null'),guest=localStorage.getItem(workspaceDraftKey(null));if(marker&&marker.raw===guest&&Date.now()-marker.at<30*60*1000&&Date.now()>=marker.at&&workspaceDraft(guest)){raw=guest;localStorage.setItem(workspaceDraftKey(user.id),raw);localStorage.removeItem(workspaceDraftKey(null));}sessionStorage.removeItem(workspaceAuthKey);}catch{}}
   let legacyDraft=false;try{const old=JSON.parse(localStorage.getItem('bookuno.onboarding.draft.v1')||'null');legacyDraft=!!old?.bizType&&(!user||String(old.email||'').toLowerCase()===String(user.email||'').toLowerCase());}catch{}
   const draft=workspaceDraft(raw);if(!live||scope.current!==tag)return;
   setForm(recovery?recovery.input:draft?.form||workspaceBlank());setStep(recovery?3:draft?.step||1);setSource({loading:false,user,recovery,pending:!!pending,legacyDraft,legacyCreation:!!user&&!recovery&&!!localStorage.getItem('bookuno.onboarding.creation.'+user.id),error:''});
  }catch(e){if(live&&scope.current===tag)setSource({loading:false,user:null,recovery:null,pending:false,error:e?.message||'Your setup could not be loaded.'});}}
  load();
  const changed=async()=>{try{const actor=(await window.BOOKUNO_API.getSession())?.user?.id||null;if(live&&scope.current===tag&&actor!==tag.actor){scope.current=null;setRevision(v=>v+1);}}catch{}};
  const storage=e=>{if(!e.key||e.key==='bookuno.local_test_session'||/auth-token/.test(e.key))changed();};
  const auth=window.BOOKUNO_API.onAuthStateChange?.(event=>{if(['SIGNED_IN','SIGNED_OUT','USER_UPDATED'].includes(event))changed();});
  window.addEventListener('storage',storage);window.addEventListener('bookuno-auth-changed',changed);
  return()=>{live=false;if(scope.current===tag)scope.current=null;auth?.data?.subscription?.unsubscribe?.();window.removeEventListener('storage',storage);window.removeEventListener('bookuno-auth-changed',changed);};
 },[revision]);
 React.useEffect(()=>{if(source.loading||source.error||source.recovery?.completed||scope.current?.actor!==(source.user?.id||null))return;try{const raw=JSON.stringify({version:1,form,step});localStorage.setItem(workspaceDraftKey(source.user?.id),raw);draftRaw.current=raw;}catch{setWarning('This browser could not keep your draft. Keep this page open; saving a workspace requires recovery storage.');}},[form,step,source.loading,source.error,source.user?.id,source.recovery?.completed]);
 React.useEffect(()=>{if(!source.loading)heading.current?.focus({preventScroll:false});},[step,source.loading]);
 const locked=busy||!!source.recovery,options=window.BOOKUNO_TOOLS.options;
 function field(key,value){if(locked)return;setError('');setForm(f=>({...f,[key]:value}));}
 function exit(event){if(source.loading||source.error||source.recovery?.completed)return;try{if(scope.current?.actor!==(source.user?.id||null))throw Error('Your account changed. Reload before saving this draft.');localStorage.setItem(workspaceDraftKey(source.user?.id),JSON.stringify({version:1,form,step}));}catch(e){event.preventDefault();setError(e?.message||'Your draft could not be saved. Keep this page open.');}}
 function next(event){event.preventDefault();if(busy||source.recovery)return;setError('');try{if(step===1&&!form.tools.length)throw Error('Choose at least one tool to start with.');if(step===2)window.BOOKUNO_SETUP.normalise(form);setStep(s=>Math.min(s+1,3));}catch(e){setError(e.message);}}
 function auth(event,mode){event.preventDefault();try{window.BOOKUNO_SETUP.normalise(form);const raw=JSON.stringify({version:1,form,step:3});localStorage.setItem(workspaceDraftKey(null),raw);sessionStorage.setItem(workspaceAuthKey,JSON.stringify({raw,at:Date.now()}));window.location.href='/app.html#/auth?type=business&mode='+mode+'&next=business%2Fstart';}catch(e){setError(e?.message||'Your draft could not be saved before sign-in.');}}
 async function create(event){event.preventDefault();if(!source.user)return;const tag=scope.current,actor=source.user.id;if(!tag||tag.actor!==actor||running.current===tag)return;running.current=tag;setBusy(true);setError('');
  try{const input=window.BOOKUNO_SETUP.normalise(form),result=await window.BOOKUNO_API.createWorkspace({expected_actor_id:actor,input});if(!result?.verified||result.tools?.actor_id!==actor)throw Error('Your workspace could not be confirmed.');if(scope.current!==tag||(await window.BOOKUNO_API.getSession())?.user?.id!==actor)return;
   try{const key=workspaceDraftKey(actor);if(localStorage.getItem(key)===draftRaw.current)localStorage.removeItem(key);}catch{}
   const tour=workspaceTourIntent();
   try{window.BOOKUNO_ANALYTICS?.track?.('workspace_setup_completed',{tools:input.tools,plan:'free',business_id:result.business.id,...(tour?{tour_plan:tour.plan}:{})});}catch{}
   // A tour operator goes straight to the plan screen with their chosen plan shown first. Nothing is started here.
   if(tour){window.BOOKUNO_TOUR_INTENT.bind(result.business.id);window.location.href='/business-app/app.html#plan';return;}
   window.location.href='/business-app/app.html#today';
  }catch(e){if(scope.current===tag){setError(e?.message||'Your workspace could not be confirmed. Retry the same setup.');try{const recovery=await window.BOOKUNO_API.getWorkspaceSetupRecovery();if(scope.current===tag)setSource(s=>({...s,recovery}));}catch{if(scope.current===tag)setSource(s=>({...s,recovery:{input:form,businessId:null,completed:false}}));}}}
  finally{if(running.current===tag)running.current=null;if(scope.current===tag)setBusy(false);}}
 async function openSaved(){const tag=scope.current;if(!tag||running.current===tag)return;running.current=tag;setBusy(true);setError('');try{const result=await window.BOOKUNO_API.openWorkspaceSetup();if(result.verified&&scope.current===tag)window.location.href='/business-app/app.html#'+(source.recovery?.completed?'today':'workspace');}catch(e){if(scope.current===tag)setError(e?.message||'Your saved workspace could not be opened.');}finally{if(running.current===tag)running.current=null;if(scope.current===tag)setBusy(false);}}
 async function another(){const tag=scope.current;if(!tag||running.current===tag)return;running.current=tag;setBusy(true);setError('');try{await window.BOOKUNO_API.startAnotherWorkspace();if(scope.current!==tag)return;localStorage.removeItem(workspaceDraftKey(source.user?.id));setForm(workspaceBlank());setStep(1);setRevision(v=>v+1);}catch(e){if(scope.current===tag)setError(e?.message||'The previous setup still needs checking.');}finally{if(running.current===tag)running.current=null;if(scope.current===tag)setBusy(false);}}
 if(source.pending)return <OnboardingSetupRecovery/>;
 if(source.legacyCreation)return <div className="web clarity-site clarity-setup"><main className="setup-main"><section className="setup-panel"><span className="cs-eyebrow">{uiText("Previous setup")}</span><h1>{uiText("Your previous setup needs a check.")}</h1><p>{uiText("A service setup was started with this account. Resume those original details before starting a different workspace.")}</p><div className="setup-actions"><a className="cs-button cs-primary" href="/app.html#/business/legacy-setup">{uiText("Resume previous setup")}</a><a className="cs-button cs-secondary" href="/">{uiText("Back to Bookuno")}</a></div></section></main></div>;
 const titles=['What would you like to manage?','A few business details.','Your workspace, ready to begin.'],tour=workspaceTourIntent(),tourName=tour&&window.BOOKUNO_TOUR_INTENT.name(tour.plan);
 return <div className="web clarity-site clarity-setup"><header className="cs-header"><div className="cs-wrap cs-nav"><a className="cs-logo" href="/" aria-label={uiText("Bookuno home")}><img src="/business-app/brand/frame-lockup-blue.svg" alt="Bookuno" width="171" height="40"/></a><a className="setup-exit" href="/" onClick={exit}>{uiText("Save & exit")}</a></div></header><main className="setup-main">
  {source.loading?<div role="status" className="setup-loading">{uiText("Checking your account and saved setup…")}</div>:source.error?<section className="setup-panel"><h1 ref={heading} tabIndex="-1">{uiText("Let’s check your setup.")}</h1><p role="alert">{uiText(source.error)}</p><button className="cs-button cs-primary" onClick={()=>setRevision(v=>v+1)}>{uiText("Reload setup")}</button></section>:source.recovery?.completed?<section className="setup-panel"><span className="cs-eyebrow">{uiText("Saved workspace")}</span><h1 ref={heading} tabIndex="-1">{uiText("Your saved workspace.")}</h1><p><strong>{source.recovery.input.name}</strong>{uiText(" has a saved setup on this device. We’ll check your access before opening it.")}</p><p className="setup-note">{uiText("Your saved workspace is preserved when this page is refreshed.")}</p>{error&&<p role="alert" className="setup-error">{uiText(error)}</p>}<div className="setup-actions"><button className="cs-button cs-primary" disabled={busy} onClick={openSaved}>{busy?uiText("Checking…"):uiText("Open my workspace")}<ClarityGlyph kind="arrow"/></button><button className="setup-text-button" disabled={busy} onClick={another}>{uiText("Set up another business")}</button></div></section>:<>
   <nav className="setup-progress" aria-label={uiText("Workspace setup — step ")+step+uiText(" of 3")}>{['Your tools','Business details','Review & open'].map((label,i)=><span key={label} aria-current={step===i+1?'step':undefined}><span>{step>i+1?'✓':i+1}</span>{uiText(label)}</span>)}</nav>
   <section className="setup-panel"><span className="cs-eyebrow">{uiText("Step ")}{step}{tourName?uiText(" of 3 · ")+tourName:uiText(" of 3 · Free workspace")}</span><h1 ref={heading} tabIndex="-1">{titles[step-1]}</h1><p>{step===1?uiText("Choose any combination. Start with what you need; add more whenever your business grows."):step===2?uiText("Your business name and contact email appear on your Bookuno page. You can refine the rest from your workspace."):uiText("Check the details below. Your workspace starts empty, ready for your real products and offerings.")}</p>
    <form onSubmit={step<3?next:create}>
     {step===1&&<fieldset disabled={locked} className="setup-tools"><legend className="setup-visually-hidden">{uiText("Choose workspace tools")}</legend>{options.map(o=><label key={o.key} className={form.tools.includes(o.key)?'selected':''}><input type="checkbox" checked={form.tools.includes(o.key)} onChange={e=>field('tools',window.BOOKUNO_TOOLS.canonical(e.target.checked?[...form.tools,o.key]:form.tools.filter(k=>k!==o.key)))}/><span><strong>{o.title}</strong><span>{o.description}</span></span></label>)}</fieldset>}
     {step===2&&<fieldset disabled={locked} className="setup-fields"><legend className="setup-visually-hidden">{uiText("Business details")}</legend><label htmlFor="setup-business-name">{uiText("Business name")}<input id="setup-business-name" name="businessName" value={form.name} onChange={e=>field('name',e.target.value)} maxLength={160} autoComplete="organization" required/></label><label htmlFor="setup-business-email">{uiText("Business contact email")}<span>{uiText("Shown to customers on your Bookuno page.")}</span><input id="setup-business-email" name="businessEmail" type="email" value={form.email} onChange={e=>field('email',e.target.value)} maxLength={254} autoComplete="email" required/></label><div className="setup-field-pair"><label htmlFor="setup-currency">{uiText("Business currency")}<select id="setup-currency" value={form.currency} onChange={e=>field('currency',e.target.value)}>{[['gbp','GBP · British pound'],['eur','EUR · Euro'],['usd','USD · US dollar'],['cad','CAD · Canadian dollar'],['aud','AUD · Australian dollar']].map(([v,l])=><option key={v} value={v}>{uiText(l)}</option>)}</select></label><label htmlFor="setup-timezone">{uiText("Time zone")}<input id="setup-timezone" value={form.timezone} onChange={e=>field('timezone',e.target.value)} list="setup-timezones" required maxLength={80}/><datalist id="setup-timezones">{['Europe/London','Europe/Dublin','Europe/Paris','America/New_York','America/Chicago','America/Los_Angeles','America/Toronto','Australia/Sydney','Australia/Perth','Pacific/Auckland'].map(z=><option key={z} value={z}/>)}</datalist></label></div><p className="setup-note">{uiText("Prices use your chosen currency. Booking dates and times use this time zone. Payment collection is set up separately.")}</p></fieldset>}
     {step===3&&<><dl className="setup-review"><div><dt>{uiText("Business")}</dt><dd>{form.name}</dd></div><div><dt>{uiText("Customer contact")}</dt><dd>{form.email}</dd></div><div><dt>{uiText("Currency & time zone")}</dt><dd>{form.currency.toUpperCase()} · {form.timezone}</dd></div><div><dt>{uiText("Your tools")}</dt><dd>{options.filter(o=>form.tools.includes(o.key)).map(o=><span key={o.key} className="setup-tool-tag">{o.title}</span>)}</dd></div><div><dt>{uiText("Plan")}</dt><dd>{tourName?uiText("{0} · chosen on the next screen").replace('{0}',tourName):uiText("Free · £0 · no expiry")}</dd></div></dl><p className="setup-note">{tourName?uiText("This creates your workspace and Bookuno page. Next, your plan screen opens with {0} first: start the free trial with no card, or pay monthly. Nothing is charged until you choose.").replace('{0}',tourName):uiText("This creates your Free workspace and Bookuno page. No sample products, services, prices, opening hours, bookings, messages or charges are created. Review your offerings and booking page before sharing.")}</p>{!source.user&&<div className="setup-auth"><h2>{uiText("Sign in to open your workspace.")}</h2><p>{uiText("Your choices are saved on this device. Use an existing Bookuno account or create one.")}</p><div><a className="cs-button cs-primary" href="/app.html#/auth?type=business&mode=register&next=business%2Fstart" onClick={e=>auth(e,'register')}>{uiText("Create account")}</a><a className="cs-button cs-secondary" href="/app.html#/auth?type=business&mode=login&next=business%2Fstart" onClick={e=>auth(e,'login')}>{uiText("Sign in")}</a></div></div>}{source.user&&<p className="setup-account">{uiText("Signed in as ")}<strong>{source.user.email}</strong>{uiText(". Your account email and customer contact email can be different.")}</p>}</>}
     {warning&&<p role="status" className="setup-note">{uiText(warning)}</p>}{error&&<p role="alert" className="setup-error">{uiText(error)}</p>}{source.recovery&&!source.recovery.completed&&<p className="setup-note">{uiText("These original details are kept for safe recovery. Check this save before changing anything.")}</p>}
     <div className="setup-actions">{step>1&&!source.recovery&&<button type="button" className="cs-button cs-secondary" disabled={busy} onClick={()=>{setError('');setStep(s=>s-1);}}>{uiText("Back")}</button>}{step<3?<button className="cs-button cs-primary" type="submit" disabled={busy||step===1&&!form.tools.length}>{uiText("Continue ")}<ClarityGlyph kind="arrow"/></button>:source.user?<button className="cs-button cs-primary" type="submit" disabled={busy}>{busy?uiText("Checking saved workspace…"):source.recovery?uiText("Check original save"):tourName?uiText("Create workspace and choose plan"):uiText("Create Free workspace")}<ClarityGlyph kind="arrow"/></button>:null}{source.recovery?.businessId&&<button className="setup-text-button" type="button" disabled={busy} onClick={openSaved}>{uiText("Open saved workspace")}</button>}</div>
    </form>
   </section><p className="setup-help">{uiText("Need help? ")}<a href="mailto:hello@bookuno.co.uk">{uiText("hello@bookuno.co.uk")}</a>{source.legacyDraft&&<span>{uiText("Already part-way through service setup? ")}<a href="/app.html#/business/legacy-setup">{uiText("Resume previous setup")}</a></span>}</p>
  </>}
 </main></div>;
}
