// SwipeDeck.jsx — Renders the current swipe card, advances the DecisionTreeEngine
// on answer, and on completion calls the snapshot endpoint and routes onward.
const { useState: useSDs, useEffect: useSDe, useMemo: useSDm } = React;

function SwipeDeck({ go, state, set, mode = 'patient', lang, setLang }) {
  const [current, setCurrent] = useSDs(null);
  const [history, setHistory] = useSDs([]);
  const [value, setValue] = useSDs(null);
  const [loading, setLoading] = useSDs(false);
  const [progress, setProgress] = useSDs(0);

  // Boot — pull first card
  useSDe(() => {
    let alive = true;
    (async () => {
      const card = await window.DecisionTreeEngine.next({ mode });
      if (alive) setCurrent(card);
    })();
    return () => { alive = false; };
  }, [mode]);

  const onAnswer = async (direction, capturedValue) => {
    if (!current) return;
    // Translate the direction + captured value into a stored answer.
    let answer;
    if (current.kind === 'yesno') answer = direction; // 'yes'|'no'|'maybe'|'skip'
    else if (direction === 'no' || direction === 'skip') answer = null;
    else if (direction === 'maybe') answer = capturedValue ?? null;
    else answer = capturedValue ?? null; // 'yes' on chips/severity/teeth → keep captured value

    const nextHistory = [...history, { id: current.id, answer, direction }];
    setHistory(nextHistory);
    setProgress(p => p + 1);
    setValue(null);
    setLoading(true);

    // Persist swipe progressively so a refresh recovers
    set && set(s => ({ ...s, swipe: window.DecisionTreeEngine.complete(mode, nextHistory) }));

    const nextCard = await window.DecisionTreeEngine.next({
      mode, currentId: current.id, lastAnswer: direction, state: { ...(state||{}), history: nextHistory },
    });
    setLoading(false);

    if (!nextCard) {
      // Deck done — write final state + route
      const final = window.DecisionTreeEngine.complete(mode, nextHistory);
      set && set(s => ({
        ...s,
        swipe: final,
        teeth: final.teeth,
        toothPain: final.toothPain,
        symptoms: deriveSymptoms(final),
        severity: final.pain.level,
        interests: final.interests,
      }));
      if (mode === 'clinician') go('folio');
      else if (final.urgency_hint === 'emergency') go('emergency');
      else if (final.teeth && final.teeth.length === 0) go('audit-1');
      else go('snapshot');
      return;
    }
    setCurrent(nextCard);
  };

  if (!current) return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main><div className="container" style={{padding:'var(--s-8) 0'}}><p>Loading…</p></div></main>
      <Footer go={go}/>
    </div>
  );

  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main>
        <div className="container" style={{maxWidth:520, padding:'var(--s-6) 0'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'var(--s-3)'}}>
            <div className="t-eyebrow">{mode === 'clinician' ? 'Clinician swipe' : 'Patient swipe triage'}</div>
            <div style={{display:'flex',gap:4}} aria-hidden="true">
              {Array.from({length: Math.max(progress+1, 6)}, (_, i) => (
                <span key={i} style={{
                  width:18, height:3, borderRadius:2,
                  background: i < progress ? 'var(--ink-1)' : 'var(--ink-5)',
                }}/>
              ))}
            </div>
          </div>
          <SwipeCard card={current} value={value} onChange={setValue} onAnswer={onAnswer} mode={mode}/>
          {loading && <p style={{textAlign:'center',color:'var(--ink-3)',marginTop:8,fontSize:12}}>Loading next card…</p>}
          <div style={{textAlign:'center',marginTop:'var(--s-4)'}}>
            <button type="button" className="bc-link" style={{background:'none',border:0,cursor:'pointer',color:'var(--ink-3)',fontSize:12}}
              onClick={()=>go('audit-1')}>Skip triage — open the full Smile Audit →</button>
          </div>
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

function deriveSymptoms(final) {
  const out = [];
  if (final.pain.level >= 1) out.push('tooth pain');
  if (final.pain.triggers.includes('cold')) out.push('sensitivity to cold');
  if (final.pain.triggers.includes('hot')) out.push('sensitivity to hot');
  if (final.urgency_hint === 'emergency') out.push('swelling');
  return out;
}

window.SwipeDeck = SwipeDeck;
