import {clipFor,player} from '/app/audio.mjs';
import {conversationHistory,turnContext,sentReply,makeSubmission} from '/app/conversation.mjs';
import {glossText,responseEnglish} from '/app/language-help.mjs';
import {readProgress,writeProgress,resetProgress,newSession,makeDraft,saveDraft,finishExercise,progressSummary} from '/app/progress.mjs';
import {evaluate, evaluateChoice, shuffle, assemble, supportedExercises} from '/app/engine.mjs';

    const C = {
      yellow:    '#FFD23F',
      yellowDeep:'#E9B91A',
      red:       '#E83A2F',
      ink:       '#141210',
      cream:     '#FFF6E0',
      green:     '#1F8A52',
      blue:      '#2840B5',
      muted:     '#6E6557',
    };

    function CassolaMascot({ size = 130, expression = 'happy' }) {
      return (
        <svg viewBox="0 0 140 130" width={size} height={size * (130/140)}>
          <g transform="translate(4,4)">
            <path d="M20 38 L 120 38 L 110 110 Q 70 122 30 110 Z" fill={C.ink}/>
            <ellipse cx="70" cy="38" rx="50" ry="10" fill={C.ink}/>
          </g>
          <path d="M20 38 L 120 38 L 110 110 Q 70 122 30 110 Z" fill={C.red} stroke={C.ink} strokeWidth="4" strokeLinejoin="round"/>
          <ellipse cx="70" cy="38" rx="50" ry="10" fill={C.red} stroke={C.ink} strokeWidth="4"/>
          <ellipse cx="70" cy="35" rx="46" ry="6" fill={C.ink} opacity="0.25"/>
          <ellipse cx="14" cy="60" rx="6" ry="14" fill={C.red} stroke={C.ink} strokeWidth="4"/>
          <ellipse cx="126" cy="60" rx="6" ry="14" fill={C.red} stroke={C.ink} strokeWidth="4"/>
          <circle cx="55" cy="68" r="9" fill={C.cream} stroke={C.ink} strokeWidth="3"/>
          <circle cx="85" cy="68" r="9" fill={C.cream} stroke={C.ink} strokeWidth="3"/>
          <circle cx="56" cy="70" r="4" fill={C.ink}/>
          <circle cx="86" cy="70" r="4" fill={C.ink}/>
          <circle cx="57" cy="68" r="1.5" fill={C.cream}/>
          <circle cx="87" cy="68" r="1.5" fill={C.cream}/>
          {expression === 'happy' && <path d="M52 88 Q 70 102 88 88" stroke={C.ink} strokeWidth="4" fill="none" strokeLinecap="round"/>}
          {expression === 'oh'    && <ellipse cx="70" cy="92" rx="7" ry="9" fill={C.ink}/>}
          <circle cx="40" cy="88" r="4" fill={C.yellow} opacity="0.9"/>
          <circle cx="100" cy="88" r="4" fill={C.yellow} opacity="0.9"/>
          <path d="M55 22 Q 50 14 58 8" stroke={C.ink} strokeWidth="3" fill="none" strokeLinecap="round"/>
          <path d="M70 18 Q 65 10 73 4" stroke={C.ink} strokeWidth="3" fill="none" strokeLinecap="round"/>
          <path d="M85 22 Q 80 14 88 8" stroke={C.ink} strokeWidth="3" fill="none" strokeLinecap="round"/>
        </svg>
      );
    }

    function Sticker({ children, bg = C.red, color = C.cream, rot = -3, size = 13, style = {} }) {
      return (
        <span style={{
          display: 'inline-block', background: bg, color,
          padding: '6px 12px',
          border: `2.5px solid ${C.ink}`,
          borderRadius: 8, fontWeight: 800, fontSize: size,
          transform: `rotate(${rot}deg)`,
          boxShadow: `3px 3px 0 ${C.ink}`,
          fontFamily: "'IBM Plex Mono', monospace",
          letterSpacing: 0.5,
          lineHeight: 1,
          whiteSpace: 'nowrap',
          ...style,
        }}>{children}</span>
      );
    }

function HomeScreen({onStart,progress,lesson,progressPanel,notice}){
 const total=supportedExercises(lesson).length,finished=progress.session?.finished.length||0;
 const resuming=false;
 const revisit=progressSummary(progress).revisit;
 return <main className="home-shell">
 <header className="home-brand"><strong>cassola</strong><span>Català a foc lent.</span></header>
 <div className="home-greeting"><h1>Una mica de<br/><em>conversa?</em></h1><CassolaMascot size={112}/></div>
 <section className="home-invitation" aria-label="Walking in">
 <Sticker bg={C.yellow} color={C.ink} size={10}>ENTRANT AL RESTAURANT</Sticker>
 <h2>La primera paraula?<br/>Bona nit.</h2>
 <p>A table for two. A little Catalan.<br/>Let’s see where it takes you.</p>
 <button className="home-start" onClick={onStart}>{resuming?'CONTINUEM →':finished===total?'TORNEM-HI →':'SOM-HI →'}</button>
 {resuming&&<small>Your conversation is right where you left it.</small>}
 {!resuming&&revisit&&<small>Back for another chat?</small>}
 </section>
 {notice&&<p className="notice" role="status">{notice}</p>}
 <section className="home-next" aria-label="Coming soon"><div className="home-next-label">Encara al foc <span>· coming soon</span></div>
 <div className="future-scenes"><span className="future-scene booking">☎<span>Una reserva</span></span><span className="future-scene menu">☰<span>La carta</span></span><span className="future-scene bill">€<span>El compte</span></span></div>
 </section>
 <footer className="home-footer"><details><summary>Your practice</summary>{progressPanel}</details>
 <details><summary>A little about Cassola</summary><p>Small restaurant conversations, with Caçó by your side. Waiter lines and supported choice and build replies have trial audio, with different voices for each speaker.</p><p>Our Catalan and trial voices are awaiting native-speaker review.</p></details></footer>
 </main>;
}

const {useState,useEffect,useRef}=React;
// Lift the last two bubbles to the top of the thread (scrolling the thread, never the page, so nothing jumps).
// The spacer sits just above the reply area, so it fills the gap and keeps the reply at the bottom.
function toLatest(el){
 const thread=el?.closest('.conversation-thread'),spacer=thread?.querySelector('.thread-spacer');if(!thread)return;
 if(!spacer)return thread.scrollTo({top:thread.scrollHeight,behavior:'smooth'});
 // A new scene starts its own page; otherwise keep the last two bubbles, or just the last one if both don't fit.
 const end=thread.lastElementChild,content=end.offsetTop+end.offsetHeight+12-spacer.offsetHeight,fits=el=>content-(el.offsetTop-12)<=thread.clientHeight;
 const turn=thread.querySelectorAll('.conversation-turn'),scene=turn[turn.length-1]?.querySelector('.scene-break');
 const messages=[...thread.querySelectorAll('.chat-message')],last=messages.at(-1),before=messages.at(-2);
 const target=messages.length<2&&fits(thread.firstElementChild)?null:scene&&fits(scene)?scene:before&&fits(before)?before:last;
 const top=target?Math.max(0,target.offsetTop-12):0;
 spacer.style.height=Math.max(0,thread.clientHeight-(content-top))+'px';
 thread.scrollTo({top,behavior:'smooth'});
}
function Copy({value,english}){return value?<><div lang="ca">{value.ca}</div>{english&&value.en&&<div className="english" lang="en">{value.en}</div>}</>:null;}
function WordMeaning({text,meaning,onHelp}){
 const [open,setOpen]=useState(false),[position,setPosition]=useState({}),root=useRef(null),id=React.useId();
 function show(){const rect=root.current.getBoundingClientRect();setPosition({left:Math.max(12,Math.min(rect.left,window.innerWidth-212)),top:Math.min(rect.bottom+8,window.innerHeight-80)});setOpen(true);onHelp?.();}
 useEffect(()=>{if(!open)return;const close=event=>{if(!root.current?.contains(event.target))setOpen(false);};document.addEventListener('pointerdown',close);return()=>document.removeEventListener('pointerdown',close);},[open]);
 return <span className="word-meaning" ref={root} onPointerEnter={event=>{if(event.pointerType==='mouse')show();}} onPointerLeave={()=>setOpen(false)}>
 <button type="button" className="word" aria-label={text} aria-description="English meaning" aria-expanded={open} aria-describedby={open?id:undefined} onClick={event=>{event.stopPropagation();show();}} onFocus={event=>{if(event.target.matches(':focus-visible'))show();}} onBlur={()=>setOpen(false)} onKeyDown={event=>{if(event.key==='Escape'){setOpen(false);event.stopPropagation();}}}>{text}</button>
 {open&&<span className="word-tooltip" style={position} id={id} role="tooltip" lang="en">{meaning}</span>}</span>;
}
function Glossed({text,onHelp}){return <span lang="ca">{glossText(text).map((part,i)=>part.meaning?<WordMeaning key={i} {...part} onHelp={onHelp}/>:part.text)}</span>;}
// Only the reply that stands is shown: a failed attempt stays until the learner edits it, then the retry replaces it.
// Accepted choice and build replies have pre-generated clips; typed and spoken replies are open-ended, so stay text-only.
const LEARNER_AUDIO=['listen_choice','choice','build'];
function SentMessages({exercise,submissions,lesson,retrying=false,autoPlay=false}){
 const submission=submissions.at(-1);
 if(!submission||(submission.outcome!=='communicated'&&!retrying))return null;
 const failed=submission.outcome!=='communicated',reply=sentReply(exercise,submission),missing=submission.missing||exercise.options?.find(o=>o.id===submission.input)?.missing_details||[];
 return <>
 <div className={'chat-message learner'+(failed?' failed':'')} aria-label={exercise.id==='listen-booking'?'Your interpretation':'Your reply'}>{!failed&&LEARNER_AUDIO.includes(exercise.type)?<div className="waiter-line"><AudioButton lesson={lesson} staff={{ca:reply.ca}} autoPlay={autoPlay}/><Copy value={reply}/></div>:<Copy value={reply}/>}</div>
 {failed&&<div className="delivery">Torna-ho a provar · Try again</div>}
 {failed&&<div className="chat-coaching" lang="en">{submission.outcome==='needs_information'&&missing.length?missing.map(k=><p key={k}>{lesson.feedback.missing_details[k]?.en}</p>):submission.outcome==='uncertain'?'Your answer may be valid. The checker couldn’t recognise it.':(lesson.feedback[submission.outcome]?.en||'Add the missing detail and send again.')}</div>}
 </>;
}
const SPEAKER=<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor"/><path d="M16 8.5a5 5 0 0 1 0 7M18.5 6a8.5 8.5 0 0 1 0 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>;
// `then` lines play straight after this one, as one turn (the waiter's "És clar." + the repeated question).
// autoPlay="after" waits for whatever is playing (your answer) to finish first.
function AudioButton({lesson,staff,then=[],autoPlay=false}){
 const clips=[staff,...then].map(line=>clipFor(lesson,line)).filter(Boolean),clip=clips[0],id=React.useId(),manual=useRef(false),step=useRef(0);
 const [state,setState]=useState(player.getState);
 useEffect(()=>player.subscribe(next=>{
  if(next.key===id&&next.status==='ended'&&step.current<clips.length-1){step.current++;player.play(id,clips[step.current].path);return;}
  setState(next);
 }),[]);
 const start=()=>{step.current=0;player.play(id,clip.path);};
 // Read the line out once when it appears; browsers may block this, so failures stay silent.
 useEffect(()=>{if(!clip||!autoPlay)return;if(autoPlay==='after')return afterPlayback(start);start();},[]);
 if(!clip)return null;
 const status=state.key===id?state.status:'idle',busy=['loading','playing'].includes(status);
 return <button type="button" className={'audio-play '+status} title="Voice trial — native listening review pending" aria-label={`${busy?'Stop':'Play'}: ${[staff,...then].map(l=>l.ca).join(' ')}`} onClick={()=>{manual.current=true;busy?player.stop():start();}}>{SPEAKER}{status==='error'&&manual.current&&<span className="sr-only" role="status">Audio unavailable.</span>}</button>;
}
const Recognition=typeof window!=='undefined'&&(window.SpeechRecognition||window.webkitSpeechRecognition);
const setSession=type=>{try{if(navigator.audioSession)navigator.audioSession.type=type;}catch{}};
// Say the answer out loud; the transcript is checked like a typed answer. Typing stays as a fallback.
function SpeechInput({value,onChange,disabled}){
 const [listening,setListening]=useState(false),[typing,setTyping]=useState(!Recognition),[error,setError]=useState('');
 const rec=useRef(null);
 useEffect(()=>()=>rec.current?.abort(),[]);
 function start(){
  player.stop();setSession('play-and-record');
  const r=new Recognition();r.lang='ca-ES';r.interimResults=true;r.continuous=false;
  r.onresult=event=>onChange([...event.results].map(x=>x[0].transcript).join(' ').trim());
  r.onerror=event=>setError(['not-allowed','service-not-allowed'].includes(event.error)?'Microphone access is blocked. You can type instead.':event.error==='no-speech'?'I didn’t hear anything. Try again.':'Speech recognition didn’t work. Try again, or type instead.');
  r.onend=()=>{setListening(false);rec.current=null;setSession('playback');};
  rec.current=r;setError('');setListening(true);
  try{r.start();}catch{setListening(false);setError('Speech recognition didn’t work. Try again, or type instead.');}
 }
 if(typing)return <div><label className="sr-only" htmlFor="answer">La teva resposta</label><textarea id="answer" placeholder="Escriu la teva resposta…" value={value} disabled={disabled} maxLength={500} rows={3} spellCheck lang="ca" onChange={event=>onChange(event.target.value)}/>{Recognition&&<button type="button" className="text-button undo" onClick={()=>setTyping(false)}>🎙 Parla-ho / Speak instead</button>}</div>;
 return <div className="speech">
  <div className={'speech-transcript'+(value?'':' empty')} lang="ca" aria-live="polite">{value||(listening?'T’escolto…':'Prem el micròfon i parla.')}</div>
  <button type="button" className={'mic'+(listening?' listening':'')} disabled={disabled} aria-label={listening?'Stop listening':'Speak your answer'} onClick={()=>listening?rec.current?.stop():start()}>
   <svg viewBox="0 0 24 24" width="26" height="26" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3" fill="currentColor"/><path d="M6 11a6 6 0 0 0 12 0M12 17v4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
  </button>
  {error&&<p className="speech-error" role="status" lang="en">{error}</p>}
  <button type="button" className="text-button undo" onClick={()=>{rec.current?.abort();setTyping(true);}}>⌨ Escriu-ho / Type instead</button>
 </div>;
}
// The waiter waits for your answer to finish being read out, then a short beat, before speaking.
function afterPlayback(fn){
 let t=null;const busy=()=>['loading','playing'].includes(player.getState().status);
 if(!busy()){fn();return()=>{};}
 const off=player.subscribe(()=>{if(!busy()){off();t=setTimeout(fn,350);}});
 return()=>{off();clearTimeout(t);};
}
function ConversationTurn({exercise,previous,lesson,submissions,children,onHelp,active=false,retrying=false,readReply=false}){
 const context=turnContext(lesson,exercise,previous);
 // New turns reveal one bubble at a time: scene, waiter, then your reply.
 const [stage,setStage]=useState(active&&!submissions.length?0:2);
 const root=useRef(null);
 useEffect(()=>{if(active&&stage>0)toLatest(root.current);},[stage]);
 useEffect(()=>{if(stage>=2)return;let undo=()=>{};const t=setTimeout(()=>{undo=stage===0?afterPlayback(()=>setStage(1)):(setStage(stage+1),()=>{});},stage===0?(context.scene?700:0):(context.staff?1500:0));return()=>{clearTimeout(t);undo();};},[stage]);
 return <section ref={root} className="conversation-turn" aria-label={active?'Current conversation turn':'Earlier conversation turn'}>
 {context.scene&&(previous?<div className="scene-break"><div className="kicker">NOVA ESCENA · NEW SCENE</div><Glossed text={context.scene.ca}/></div>:<div className="scene-message"><Glossed text={context.scene.ca}/></div>)}
 {context.staff&&stage>=1&&<div className="chat-message waiter"><div className="waiter-line"><AudioButton lesson={lesson} staff={exercise.staff} autoPlay={active&&stage===1}/><Glossed text={exercise.staff.ca} onHelp={onHelp}/></div></div>}
 {stage>=2&&<>
 <div className="chat-instruction"><Glossed text={context.instruction.ca}/></div>
 <SentMessages exercise={exercise} submissions={submissions} lesson={lesson} retrying={retrying} autoPlay={readReply}/>
 {submissions.at(-1)?.outcome==='communicated'&&exercise.on_success&&<div className="chat-message waiter"><div className="waiter-line"><AudioButton lesson={lesson} staff={exercise.on_success.acknowledgement} then={exercise.on_success.action==='replay_staff'?[exercise.staff]:[]} autoPlay={readReply&&'after'}/><div><Copy value={exercise.on_success.acknowledgement}/><Copy value={exercise.staff}/></div></div></div>}
 {children}
 </>}
 </section>;
}
function Exercise({exercise:e,previousExercise,lesson,onFinish,onDraft,draft}){
 const rule=lesson.answer_rules.find(r=>r.id===e.rule_id),situation=lesson.situations.find(s=>s.id===e.situation_id);
 const [initial]=useState(()=>draft||makeDraft(e,shuffle(e.options||e.chunks||[])));
 const [order]=useState(()=>initial.order.map(id=>(e.options||e.chunks||[]).find(x=>x.id===id)));
 const [picked,setPicked]=useState(initial.picked),[chunks,setChunks]=useState(initial.chunks),[answer,setAnswer]=useState(initial.answer);
 const [result,setResult]=useState(initial.result),[previous,setPrevious]=useState(initial.previous),[assisted,setAssisted]=useState(initial.assisted);
 const [submissions,setSubmissions]=useState(initial.submissions);
 // Keep legacy flags in persisted drafts so existing sessions resume without migration.
 useEffect(()=>{onDraft({id:e.id,order:initial.order,picked,chunks,answer,english:initial.english,hint:initial.hint,model:initial.model,result,previous,assisted,submissions});},[picked,chunks,answer,result,previous,assisted,submissions]);
 const anchor=useRef(null);
 useEffect(()=>{toLatest(anchor.current);},[submissions.length]);
 // The reply area mounts after the waiter bubble is revealed, so focus it when it arrives.
 const attach=el=>{if(el&&!anchor.current){anchor.current=el;toLatest(el);el.querySelector('input,textarea,button')?.focus({preventScroll:true});}};
 // Older saved drafts may already have a successful answer awaiting Continue.

 const typed=e.type==='type',built=e.type==='build',choice=!!e.options,success=result?.outcome==='communicated';
 const help=()=>{if(!success)setAssisted(true);};
 function changed(fn){fn();setResult(null);}
 function check(event){event.preventDefault();if(success)return;
  const next=choice?evaluateChoice(e,picked):evaluate({text:built?assemble(e.chunks,chunks):answer,rule,facts:situation.facts,known:e.known_to_staff||{},previous});
  const sent=[...submissions,makeSubmission(e,{picked,chunks,answer,assisted,result:next})];
  if(next.outcome==='communicated'){
   onFinish({id:e.id,outcome:'communicated',assisted},{id:e.id,order:initial.order,picked,chunks,answer,english:initial.english,hint:initial.hint,model:initial.model,result:next,previous,assisted,submissions:sent});return;
  }
  setSubmissions(sent);setResult(next);if(next.outcome==='needs_information'&&!choice)setPrevious(next.details);
  if(next.outcome!=='communicated')setAssisted(true);
 }
 const modelText=rule.accepted_responses[0].replace(/\{(\w+)\}/g,(_,k)=>situation.facts[k]??'');
 return <ConversationTurn exercise={e} previous={previousExercise} lesson={lesson} submissions={submissions} onHelp={help} active retrying={!!result&&!success}>
  <div className="thread-spacer" aria-hidden="true"/>
  <div ref={attach} className="reply-area exercise">
  {!success&&<form onSubmit={check} aria-label="Compose a reply">
  <div className="composer-label">{built?'Construeix la resposta':typed?'Digues la resposta':'Tria la resposta'}</div>
   {choice&&<fieldset><legend className="sr-only">La teva resposta</legend><div className="choices">{order.map(o=><div key={o.id} className={'choice '+(picked===o.id?'selected':'')} onClick={event=>{if(!success&&!event.target.closest('button'))changed(()=>setPicked(o.id));}}><input type="radio" name={e.id} aria-label={o.text.ca} value={o.id} disabled={success} checked={picked===o.id} onChange={()=>changed(()=>setPicked(o.id))}/><div><Glossed text={o.text.ca} onHelp={help}/></div></div>)}</div></fieldset>}
   {built&&<fieldset disabled={success}><legend className="sr-only">Construeix la resposta</legend><div className="assembly" aria-live="polite">{chunks.length?chunks.map((id,i)=><button className="chunk selected" type="button" key={id} aria-label={`Remove chunk ${i+1}: ${e.chunks.find(c=>c.id===id).text}`} onClick={()=>changed(()=>setChunks(chunks.filter(c=>c!==id)))}>{e.chunks.find(c=>c.id===id).text}</button>):<span className="english">La teva frase…</span>}</div><div className="chunks">{order.map(c=><button className="chunk" type="button" key={c.id} disabled={success||chunks.includes(c.id)} onClick={()=>changed(()=>setChunks([...chunks,c.id]))}>{c.text}</button>)}</div><button className="text-button undo" type="button" disabled={!chunks.length||success} onClick={()=>changed(()=>setChunks(chunks.slice(0,-1)))}>↶ Desfés</button></fieldset>}
   {typed&&<SpeechInput value={answer} disabled={success} onChange={text=>changed(()=>setAnswer(text))}/>}
   {result&&!choice&&<div className="chat-coaching"><span lang="en">You could say:</span> <span lang="ca">{modelText}</span></div>}
   <button className="primary send" type="submit" disabled={choice?picked===null:built?!chunks.length:!answer.trim()}>ENVIA ↑</button>
  </form>}
  {success&&<button className="primary" onClick={()=>onFinish({id:e.id,outcome:'communicated',assisted})}>Continua la conversa →</button>}
  </div>
 </ConversationTurn>;
}

function PracticeScreen({lesson,onExit,progress,onChange,storageNotice}){
 const exercises=supportedExercises(lesson),attempts=progress.session.finished,index=attempts.length;
 const history=conversationHistory(lesson,progress),end=useRef(null);
 // Each scene is its own conversation: show only this scene's turns, and pause between scenes.
 const scene=exercises[Math.min(index,exercises.length-1)].situation_id;
 const [open,setOpen]=useState(scene),between=index<exercises.length&&index>0&&scene!==open;
 const last=between?index-1:Math.min(index,exercises.length-1);
 let first=last;while(first>0&&exercises[first-1].situation_id===exercises[last].situation_id)first--;
 // Don't stop on every turn change: the answer you just gave is still being read out.
 useEffect(()=>{toLatest(end.current);},[index]);
 useEffect(()=>()=>player.stop(),[]);
 useEffect(()=>{const pause=()=>{if(document.hidden)player.stop();};document.addEventListener('visibilitychange',pause);return()=>document.removeEventListener('visibilitychange',pause);},[]);
 const justAccepted=useRef(null);
 function next(attempt,snapshot){if(attempt.outcome==='communicated')justAccepted.current=attempt.id;onChange(p=>finishExercise(snapshot?saveDraft(p,snapshot):p,attempt,lesson));}
 return <div className="lesson-shell conversation-shell">
 <header className="conversation-header"><button className="text-button" onClick={onExit} aria-label="Exit conversation">←</button><div><strong>Al restaurant</strong><span>amb en Caçó</span></div><CassolaMascot size={42}/></header>
 {storageNotice&&<p className="notice" role="status">{storageNotice}</p>}
 <div className="conversation-thread" aria-label="Restaurant conversation">
 {history.map(({exercise,step,submissions},i)=>i>=first&&<ConversationTurn key={exercise.id} exercise={exercise} previous={i>0&&exercises[i-1].situation_id===exercise.situation_id?exercises[i-1]:undefined} lesson={lesson} submissions={submissions} readReply={justAccepted.current===exercise.id}>{!submissions.length&&<p className="chat-instruction" lang="en">{step.outcome==='skipped'?'Previously left for later.':'Earlier reply was not saved.'}</p>}</ConversationTurn>)}
 {between?<div className="chat-ending"><h2>Escena feta!</h2><p lang="en">Next: {lesson.situations.find(s=>s.id===scene).context.en}</p><button className="primary" onClick={()=>setOpen(scene)}>SEGÜENT ESCENA →</button><button className="text-button" onClick={onExit}>Inici / Home</button></div>:index<exercises.length?<Exercise key={exercises[index].id} exercise={exercises[index]} previousExercise={index>first?exercises[index-1]:undefined} lesson={lesson} draft={progress.session.draft} onDraft={draft=>onChange(p=>saveDraft(p,draft))} onFinish={next}/>:<div className="chat-ending"><h2>Fins aviat!</h2><p lang="en">You communicated {attempts.filter(a=>a.outcome==='communicated').length} arrival goals with support. An independent conversation comes later.</p><button className="primary" onClick={()=>{setOpen(exercises[0].situation_id);onChange(p=>({...p,session:newSession()}));}}>TORNEM A PARLAR →</button><button className="text-button" onClick={onExit}>Inici / Home</button></div>}
 <div ref={end}/>
 </div></div>;
}
function ProgressPanel({progress,lesson,onReset}){
 const [confirm,setConfirm]=useState(false);
 const stats=progressSummary(progress),visited=progress.session?.finished.length||0,total=supportedExercises(lesson).length;
 return <div className="panel" lang="en"><strong>Walking in</strong>
 <p>{stats.communicated}/{total} goals practised · {stats.runs} conversations finished.</p>
 {progress.session&&<p>Current run: {visited}/{total} replies finished{visited<total?' — pick up anytime.':'.'}</p>}

 {stats.revisit&&<p>Ready for another chat? Your earlier practice is saved.</p>}
 {progress.lastActivity!==null&&<p className="english">Last activity: {new Date(progress.lastActivity).toLocaleString()}</p>}
 {progress.previousVersions.map((v,i)=><p className="english" key={i}>Earlier lesson {v.version}: {v.evidence.communicated.length} guided goals, {v.evidence.runs} runs. Kept separately from this version.</p>)}
 <p className="english">Saved in this browser.</p>
 {confirm?<div><p>Erase all Walking in learner progress in this browser? Native reviews are unaffected.</p><button className="small" onClick={()=>{onReset();setConfirm(false);}}>Erase progress</button> <button className="small" onClick={()=>setConfirm(false)}>Cancel</button></div>:<button className="small" onClick={()=>setConfirm(true)}>Reset learner progress</button>}
 </div>;
}
function App(){
 const [screen,setScreen]=useState('home'),[lesson,setLesson]=useState(null),[error,setError]=useState(''),[reload,setReload]=useState(0);
 const [progress,setProgress]=useState(null),[notice,setNotice]=useState(''),[storageError,setStorageError]=useState('');
 const progressRef=useRef(null);
 const storage={getItem:key=>window.localStorage.getItem(key),setItem:(key,value)=>window.localStorage.setItem(key,value),removeItem:key=>window.localStorage.removeItem(key)};
 function change(update){const next=update(progressRef.current);progressRef.current=next;setProgress(next);const saved=writeProgress(storage,next);setStorageError(saved?'':'Progress cannot be saved in this browser. You can continue for now; a reload may restore older progress or lose this session.');}
 function reset(){const result=resetProgress(storage,lesson);progressRef.current=result.progress;setProgress(result.progress);setNotice('');setStorageError(result.removed?'':'Progress was cleared for this session, but browser storage could not be erased. Older progress may return after reload.');}
 useEffect(()=>{const controller=new AbortController();setError('');fetch('/content/walking-in.v2.json',{signal:controller.signal}).then(r=>{if(!r.ok)throw Error('Lesson unavailable');return r.json();}).then(data=>{if(data.schema_version!==2||!Array.isArray(data.exercises)||!Array.isArray(data.answer_rules)||!Array.isArray(data.situations))throw Error('Invalid lesson');const loaded=readProgress(storage,data);progressRef.current=loaded.progress;setProgress(loaded.progress);setNotice(loaded.notice);setLesson(data);}).catch(e=>{if(e.name!=='AbortError')setError('We couldn’t load the lesson. Please try again.');});return()=>controller.abort();},[reload]);
 if(!lesson||!progress)return <div className="lesson-shell" role="status"><p>{error||'Carregant… / Loading…'}</p>{error&&<button className="primary" onClick={()=>setReload(reload+1)}>Try again</button>}</div>;
 const panel=<ProgressPanel progress={progress} lesson={lesson} onReset={reset}/>;
 if(screen==='practice')return <PracticeScreen lesson={lesson} progress={progress} onChange={change} storageNotice={storageError||notice} onExit={()=>setScreen('home')}/>;
 return <HomeScreen progress={progress} lesson={lesson} progressPanel={panel} notice={storageError||notice} onStart={()=>{change(p=>({...p,session:newSession(),lastActivity:Date.now()}));setScreen('practice');}}/>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
