// Kiosk screens B: Questionnaire, Position, PhotoCapture, Voice, Breath, Done

const { useState: useStateB, useEffect: useEffectB, useMemo: useMemoB, useRef: useRefB } = React;

// ── 7. QUESTIONNAIRE ──────────────────────────────────────
const QUESTIONS = [
  { q:'Do you brush your teeth twice a day?',          opts:['Every day','Most days','Not always','Almost never']},
  { q:'Do your gums bleed when you brush or floss?',   opts:['Never','Sometimes','Often','I\u2019m not sure']},
  { q:'How often do you floss?',                        opts:['Daily','A few times a week','Rarely','Never']},
  { q:'Do you use tobacco or smoke?',                   opts:['No, never','I quit','Occasionally','Daily']},
  { q:'Are your teeth sensitive to hot or cold?',      opts:['No','A little','Quite sensitive','Very sensitive']},
  { q:'Does your mouth ever feel dry?',                 opts:['Almost never','Sometimes','Often','Most of the time']},
  { q:'Any tooth pain right now?',                      opts:['None','Mild','Moderate','Sharp / severe']},
  { q:'When was your last dental visit?',               opts:['Past 6 months','6\u201312 months','1\u20132 years','Longer / never']},
  { q:'Do you snore at night?',                         opts:['No','Sometimes','Often','I don\u2019t know']},
  { q:'Have you noticed any discolouration on a tooth?',opts:['No','One spot','A few spots','Many spots']},
  { q:'Any sore patches inside your mouth?',           opts:['No','One small area','Multiple areas','Painful']},
  { q:'Are you concerned about your breath?',           opts:['No','Sometimes','Often','Yes, very']},
];

function QuestionnaireScreen({ onDone, onBack }) {
  const [i, setI] = useStateB(0);
  const [answers, setAnswers] = useStateB({});
  const [pickedIdx, setPickedIdx] = useStateB(null);
  const q = QUESTIONS[i];

  const select = (idx) => {
    setPickedIdx(idx);
    setAnswers(a => ({ ...a, [i]: idx }));
    setTimeout(() => {
      setPickedIdx(null);
      if (i < QUESTIONS.length - 1) setI(i + 1);
      else onDone(answers);
    }, 320);
  };

  return (
    <div className="quiz">
      <StatusBar stepIdx={1}/>
      <div className="quiz-head">
        <span style={{ color:'var(--ink-3)', fontFamily:'JetBrains Mono', fontSize: 13, letterSpacing:'.06em', textTransform:'uppercase' }}>
          Question {String(i+1).padStart(2,'0')} / {QUESTIONS.length}
        </span>
        <div className="quiz-prog">
          {QUESTIONS.map((_, idx) => (
            <i key={idx} className={idx < i ? 'done' : idx === i ? 'cur' : ''} />
          ))}
        </div>
      </div>
      <h2 key={i} className="quiz-q" style={{ animation: 'swapIn .45s var(--ease-out)' }}>{q.q}</h2>
      <div className="quiz-opts">
        {q.opts.map((o, idx) => (
          <button key={idx} className={`quiz-opt ${pickedIdx === idx ? 'sel' : ''}`}
                  onClick={() => select(idx)}
                  style={{ animation: `rise .5s var(--ease-out) ${0.05 * idx}s both` }}>
            <span><span className="letter">{String.fromCharCode(65 + idx)}.</span>  {o}</span>
            <svg width="20" height="14" viewBox="0 0 24 18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9h18M14 2l7 7-7 7"/></svg>
          </button>
        ))}
      </div>
      <div className="quiz-foot">
        <button className="btn-ghost" onClick={i === 0 ? onBack : () => setI(i-1)}>← Previous</button>
        <span>Tip · Tap an answer to continue</span>
      </div>
    </div>
  );
}

// ── 8. POSITION FACE ──────────────────────────────────────
function PositionScreen({ onReady, onBack }) {
  // Animation timeline: 0–2s "no face", 2–4s "centering... +14px", 4–6s "almost there", 6s+ "aligned"
  const [phase, setPhase] = useStateB('searching');
  useEffectB(() => {
    const t1 = setTimeout(() => setPhase('centering'), 1800);
    const t2 = setTimeout(() => setPhase('aligned'), 4500);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  const checks = [
    { k:'cam',  l:'Camera connected',           on: true },
    { k:'face', l:'Face detected',              on: phase !== 'searching' },
    { k:'dist', l:'Distance to scanner (40 cm)', on: phase !== 'searching' },
    { k:'cent', l:'Centered in frame',          on: phase === 'aligned' },
    { k:'mot',  l:'Camera arm calibrated',      on: true },
  ];
  const statusLabel =
    phase === 'searching' ? 'Searching for face…' :
    phase === 'centering' ? 'Centering · +14 px' :
                            'Aligned · hold still';

  return (
    <div className="position">
      <StatusBar stepIdx={2}/>
      <div className="pos-info">
        <h1>Let's get into position.</h1>
        <p>Sit comfortably. Look straight at the screen — the scanner will move into place on its own.</p>
        <div className="pos-checks stagger">
          {checks.map((c, i) => (
            <div key={c.k} className={`pos-check ${c.on ? 'ok' : ''}`} style={{ animationDelay: `${0.1 + i * 0.06}s`}}>
              <span className="badge">{c.on ? '✓' : ''}</span>
              <span>{c.l}</span>
              <span className="spacer" />
              <span style={{ fontFamily:'JetBrains Mono', fontSize: 12, color: 'var(--ink-3)' }}>{c.on ? 'OK' : 'wait…'}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 'auto', paddingTop: 32, display:'flex', justifyContent: 'space-between', alignItems:'center' }}>
          <button className="btn-secondary" onClick={onBack}>← Back</button>
          <button className="btn-primary accent"
            disabled={phase !== 'aligned'}
            style={{ opacity: phase === 'aligned' ? 1 : .4, cursor: phase === 'aligned' ? 'pointer' : 'not-allowed' }}
            onClick={onReady}>
            I'm ready
            <span className="arrow"><svg width="18" height="14" viewBox="0 0 24 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9h18M14 2l7 7-7 7"/></svg></span>
          </button>
        </div>
      </div>
      <div className="pos-cam">
        <CameraChrome status={phase} statusLabel={statusLabel}/>
        <FaceMeshView status={phase === 'aligned' ? 'aligned' : 'searching'} drift={phase === 'centering' ? 14 : 0}/>
      </div>
    </div>
  );
}

// ── 9. PHOTO CAPTURE (13 angles) ──────────────────────────
const CAPTURE_STEPS = [
  { id:'smile',          t:'Smile · front teeth',           ref:'assets/ref-smile.png',          gif:'assets/gif-smile.gif',
    instr:['Look straight ahead.', 'Smile to show your front teeth.', 'Hold still — the scanner does the rest.'],
    conds:['mouth_open','smile_detected','head_yaw_ok']
  },
  { id:'top',            t:'Top teeth',                     ref:'assets/ref-top-teeth.png',      gif:'assets/gif-top-teeth.gif',
    instr:['Say "aaah".', 'Tilt your head back slightly.', 'Let the upper teeth show.'],
    conds:['mouth_open','head_pitch_ok','smile_detected']
  },
  { id:'top-lip',        t:'Top teeth · upper lip lifted',  ref:'assets/ref-top-upper-lip.png',  gif:'assets/gif-top-upper-lip.gif',
    instr:['Use your finger to pull your upper lip up.', 'Hold for a moment — the scanner will capture.'],
    conds:['mouth_open','upper_lip_retracted']
  },
  { id:'cheek-top-right',t:'Right side · upper teeth',      ref:'assets/ref-cheek-top-right.png',gif:'assets/gif-cheek-top-right.gif',
    instr:['Hook your finger inside your right cheek.', 'Pull gently outward.'],
    conds:['mouth_open','cheek_retracted_right']
  },
  { id:'cheek-top-left', t:'Left side · upper teeth',       ref:'assets/ref-cheek-top-left.png', gif:'assets/gif-cheek-top-left.gif',
    instr:['Hook your finger inside your left cheek.', 'Pull gently outward.'],
    conds:['mouth_open','cheek_retracted_left']
  },
  { id:'bottom',         t:'Bottom teeth',                  ref:'assets/ref-bottom-teeth.png',   gif:'assets/gif-bottom-teeth.gif',
    instr:['Open your mouth.', 'Touch your tongue to the roof of your mouth.'],
    conds:['mouth_open','head_pitch_ok']
  },
  { id:'tongue',         t:'Tongue · front',                ref:'assets/ref-tongue-front.png',   gif:'assets/gif-tongue-front.gif',
    instr:['Say "aaah" and stick your tongue all the way out.'],
    conds:['mouth_open','tongue_detected']
  },
];

const COND_LABELS = {
  mouth_open: 'Mouth open',
  smile_detected: 'Smile visible',
  head_yaw_ok: 'Head straight',
  head_pitch_ok: 'Head angle',
  upper_lip_retracted: 'Upper lip lifted',
  lower_lip_retracted: 'Lower lip pulled',
  cheek_retracted_right: 'Right cheek out',
  cheek_retracted_left: 'Left cheek out',
  tongue_detected: 'Tongue visible',
};

function PhotoCaptureScreen({ onDone, onBack }) {
  // Visual scope: 13 slots, but we cycle through CAPTURE_STEPS (7 detailed) and pad to 13 visually.
  const total = 13;
  const [stepI, setStepI] = useStateB(0);                  // index into CAPTURE_STEPS (cycles)
  const [slotI, setSlotI] = useStateB(2);                  // 0-indexed slot in the 13-strip; starts mid-flow for demo
  const [phase, setPhase] = useStateB('aligning');         // aligning → countdown → captured
  const [conds, setConds] = useStateB({});                 // active conds map
  const [flashKey, setFlashKey] = useStateB(0);

  const step = CAPTURE_STEPS[stepI % CAPTURE_STEPS.length];

  // condition reveal cadence (each cond ticks ON over ~2.4s)
  useEffectB(() => {
    setConds({});
    if (phase !== 'aligning') return;
    const timeouts = step.conds.map((k, i) =>
      setTimeout(() => setConds(c => ({ ...c, [k]: true })), 600 + i * 600)
    );
    const advance = setTimeout(() => setPhase('countdown'), 600 + step.conds.length * 600 + 200);
    return () => { timeouts.forEach(clearTimeout); clearTimeout(advance); };
  }, [phase, stepI]);

  function onCountdownDone() {
    setFlashKey(k => k + 1);
    setPhase('captured');
    setTimeout(() => {
      if (slotI + 1 >= total) {
        onDone();
      } else {
        setSlotI(s => s + 1);
        setStepI(s => s + 1);
        setPhase('aligning');
      }
    }, 900);
  }

  const statusLabel =
    phase === 'aligning'   ? `Centering · +${Math.round(8 - Object.keys(conds).length * 2)} px` :
    phase === 'countdown'  ? 'Hold still' :
                             'Captured';
  const statusClass = phase === 'captured' ? 'ok' : '';

  return (
    <div className="capture">
      <StatusBar stepIdx={2}/>
      <div className="capture-head">
        <div className="lhs">
          <span className="count">Photo {String(slotI+1).padStart(2,'0')} / {total}</span>
          <h2 key={stepI} style={{ animation: 'swapIn .4s var(--ease-out)'}}>{step.t}</h2>
        </div>
        <span className={`status-pill ${statusClass}`}>
          <span className="ldot"/> {statusLabel}
        </span>
      </div>
      <div className="capture-body">
        <div className="cap-cam" key={'cam' + slotI}>
          <CameraChrome status={phase} statusLabel="OS-Arm v3.1 · cam0" recording />
          <FaceMeshView status={phase === 'countdown' || phase === 'captured' ? 'capturing' : 'aligned'} drift={4}/>
          {phase === 'countdown' && (
            <CountdownRing from={3} key={'cd'+slotI} onDone={onCountdownDone}/>
          )}
          {phase === 'captured' && <div className="flash" key={'fl' + flashKey}/>}
        </div>
        <div className="cap-side">
          <div className="ref-card">
            <div className="lbl">Reference</div>
            <img key={'r' + stepI} src={step.ref} alt={step.t}
                 style={{ animation: 'swapIn .5s var(--ease-out)' }}/>
          </div>
          <div className="ref-card">
            <div className="lbl">Demo</div>
            <img key={'g' + stepI} src={step.gif} alt={step.t + ' demo'}
                 style={{ animation: 'swapIn .5s var(--ease-out)' }}/>
          </div>
          <div className="instr-card">
            <div className="lbl">Do this now</div>
            <ol key={'i' + stepI} style={{ animation: 'rise .5s var(--ease-out)' }}>
              {step.instr.map((line, idx) => <li key={idx}>{line}</li>)}
            </ol>
          </div>
          <div className="conds-card">
            <div className="lbl">Live alignment</div>
            <div className="conds">
              {step.conds.map(k => (
                <span key={k} className={`cond ${conds[k] ? 'ok' : ''}`}>
                  {conds[k] ? '✓' : '○'}  {COND_LABELS[k] || k}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>
      <div className="strip">
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} className={`slot ${i < slotI ? 'done' : i === slotI ? 'cur' : ''}`}>
            <span className="tick">
              {i < slotI && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-12"/></svg>}
              {i === slotI && <span style={{ display:'inline-block', width: 6, height: 6, borderRadius: '50%', background:'currentColor'}}/>}
              {i > slotI && (i+1)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 10. VOICE ──────────────────────────────────────────────
function VoiceScreen({ onDone, onBack }) {
  const [active, setActive] = useStateB(false);
  const [done, setDone] = useStateB(false);
  const t = useCountdown(20, active && !done, () => { setDone(true); setTimeout(onDone, 1200); });
  return (
    <div className="voice">
      <StatusBar stepIdx={3}/>
      <div className="vb-head stagger">
        <h1 style={{ animationDelay:'.05s' }}>Now your <em>voice</em>.</h1>
        <p style={{ animationDelay:'.15s'}}>Twenty seconds of jaw articulation. Softly open and close your mouth — that's it.</p>
      </div>
      <div className="vb-stage">
        <div className="vb-instr stagger">
          {[
            'Sit upright, mouth a few inches from the kiosk.',
            'Open and close your mouth slowly — like saying "ah-mm".',
            'Try to keep a steady rhythm.',
            'Recording stops automatically at 20 seconds.',
          ].map((s, i) => (
            <div key={i} className="item" style={{ animationDelay: `${0.15 + i * 0.06}s`}}>
              <span className="n">{String(i+1).padStart(2,'0')}</span> {s}
            </div>
          ))}
          <div style={{ marginTop: 28, display:'flex', gap: 12, alignItems:'center' }}>
            <button className="btn-secondary" onClick={onBack}>← Back</button>
            {!active && !done && (
              <button className="btn-primary accent" onClick={() => setActive(true)}>
                Start recording
                <span className="arrow"><svg width="18" height="14" viewBox="0 0 24 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9h18M14 2l7 7-7 7"/></svg></span>
              </button>
            )}
            {(active || done) && (
              <span className="mono" style={{ color: done ? 'var(--accent)' : 'var(--ink-3)' }}>
                {done ? '✓ Recording saved · 20.0 s · 44.1 kHz' : `Recording… ${String(20 - t).padStart(2,'0')} / 20 s`}
              </span>
            )}
          </div>
        </div>
        <div className="mic-stage">
          <div className="mic-halo" />
          {active && !done && <><span className="mic-ring"/><span className="mic-ring"/><span className="mic-ring"/></>}
          <div className="mic-orb">
            <svg width="76" height="76" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
              <rect x="9" y="3" width="6" height="12" rx="3"/>
              <path d="M5 11a7 7 0 0 0 14 0"/>
              <path d="M12 18v3"/>
            </svg>
            <VoiceBars active={active && !done}/>
            <span className="countdown">{active && !done ? `${20 - t} s remaining` : done ? '20.0 s complete' : 'Tap "Start recording"'}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── 11. BREATH ─────────────────────────────────────────────
function BreathScreen({ onDone, onBack }) {
  const [active, setActive] = useStateB(false);
  const [done, setDone] = useStateB(false);
  const ppb = BreathClimb({ active, target: 42, onDone: () => { setDone(true); setTimeout(onDone, 1500); }});
  return (
    <div className="breath">
      <StatusBar stepIdx={4}/>
      <div className="vb-head stagger">
        <h1 style={{ animationDelay:'.05s' }}>One more · your <em>breath</em>.</h1>
        <p style={{ animationDelay:'.15s'}}>Exhale slowly into the port for about eight seconds. We're measuring hydrogen sulphide (H₂S) — a key indicator of oral health.</p>
      </div>
      <div className="vb-stage">
        <div className="vb-instr stagger">
          {[
            'Locate the small port on the right side of the kiosk.',
            'Take a normal breath in through your nose.',
            'Press your lips around the port and exhale gently.',
            'Keep exhaling steadily for the full eight seconds.',
          ].map((s, i) => (
            <div key={i} className="item" style={{ animationDelay: `${0.15 + i * 0.06}s`}}>
              <span className="n">{String(i+1).padStart(2,'0')}</span> {s}
            </div>
          ))}
          <div style={{ marginTop: 28, display:'flex', gap: 12, alignItems:'center' }}>
            <button className="btn-secondary" onClick={onBack}>← Back</button>
            {!active && !done && (
              <button className="btn-primary accent" onClick={() => setActive(true)}>
                Start exhaling
                <span className="arrow"><svg width="18" height="14" viewBox="0 0 24 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9h18M14 2l7 7-7 7"/></svg></span>
              </button>
            )}
            {(active || done) && (
              <span className="mono" style={{ color: done ? 'var(--accent)' : 'var(--ink-3)' }}>
                {done ? '✓ Sample captured · within healthy range' : `Reading… ${ppb} ppb`}
              </span>
            )}
          </div>
        </div>
        <div className="mic-stage">
          <div className="mic-halo" />
          {active && !done && <><span className="mic-ring"/><span className="mic-ring"/></>}
          <div className="breath-orb">
            {active && <div className="breath-curtain"/>}
            <div className="reading" style={{ position:'relative', zIndex: 2 }}>
              <div className="v num">{active || done ? ppb : '—'}</div>
              <div className="u">ppb · H₂S</div>
              {done && (
                <div style={{ marginTop: 14, display:'inline-flex', alignItems:'center', gap: 8,
                              padding: '4px 12px', borderRadius: 999, background: 'var(--accent-soft)',
                              color: 'var(--accent)', fontSize: 13, fontFamily:'JetBrains Mono, monospace' }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-12"/></svg>
                  Within healthy range
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── 12. DONE ───────────────────────────────────────────────
function DoneScreen({ name = 'Priya', onFinish }) {
  // Auto-return to idle after ~30s
  useEffectB(() => {
    const t = setTimeout(onFinish, 30000);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="done-screen">
      <StatusBar stepIdx={5}/>
      <div className="done-head">
        <h1 className="serif" style={{ animation: 'rise .7s var(--ease-out)'}}>
          All done, <em>{name}.</em>
        </h1>
        <div className="done-tick">
          <svg width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-12"/></svg>
        </div>
      </div>
      <p style={{ color: 'var(--ink-3)', fontSize: 19, maxWidth: 740, lineHeight: 1.5, margin: '0 0 6px',
                  animation: 'rise .7s var(--ease-out) .1s both' }}>
        Everything's been encrypted and is on its way to your dentist. You'll get a report on your phone within 24 hours.
      </p>
      <div className="done-summary stagger">
        {[
          { l:'Questions',     v:'12',   sub:'all answered' },
          { l:'Photos',        v:'13',   sub:'captured' },
          { l:'Voice sample',  v:'20',   u:'sec', sub:'recorded' },
          { l:'Breath · H₂S',  v:'42',   u:'ppb', sub:'within range' },
        ].map((c, i) => (
          <div key={i} className="done-cell" style={{ animationDelay: `${0.25 + i * 0.06}s` }}>
            <span className="lbl">{c.l}</span>
            <span className="val num">{c.v}{c.u && <small>{c.u}</small>}</span>
            <span className="ok">✓ {c.sub}</span>
          </div>
        ))}
      </div>
      <div className="done-foot">
        <div className="done-next">
          <h4>What happens next</h4>
          <p>Dr. Anika Mehta reviews your scan within 24 hours. If anything needs attention, she'll call. Otherwise, a clean report lands in your inbox by tomorrow morning.</p>
        </div>
        <button className="btn-primary accent" onClick={onFinish}>
          Done — go home
          <span className="arrow"><svg width="18" height="14" viewBox="0 0 24 18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9h18M14 2l7 7-7 7"/></svg></span>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, {
  QuestionnaireScreen, PositionScreen, PhotoCaptureScreen, VoiceScreen, BreathScreen, DoneScreen
});
