// Kiosk screens A: Idle, Choice, SignIn, Register, Welcome, Consent

const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

// ── 1. IDLE ────────────────────────────────────────────────
function IdleScreen({ onBegin }) {
  return (
    <div className="idle" onClick={onBegin}>
      <div className="idle-hero">
        <div className="idle-mark">
          <span className="pulse" />
          <span className="pulse" />
          <svg width="120" height="120" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="9" stroke="var(--accent)" strokeWidth="1.4"/>
            <path d="M7 12c1.5-3 8-3 9.5 0" stroke="var(--accent)" strokeWidth="1.4" strokeLinecap="round"/>
            <path d="M9 8.5h6" stroke="var(--accent)" strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
        </div>
      </div>
      <div style={{ textAlign: 'center', padding: '0 80px' }}>
        <h1 className="serif">
          A quick check<br/>on your <em>smile.</em>
        </h1>
      </div>
      <div className="idle-foot">
        <div className="idle-tap">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 4v8"/><path d="M8 8l4-4 4 4"/><circle cx="12" cy="17" r="3"/>
          </svg>
          Tap anywhere to begin
        </div>
        <div className="idle-meta">
          <b>Smile Dental · Bandra W</b><br/>
          About 6 minutes · Walk-in queue: 2 ahead
        </div>
      </div>
    </div>
  );
}

// ── 2. CHECK-IN CHOICE ─────────────────────────────────────
function ChoiceScreen({ onReturning, onNew }) {
  return (
    <div className="choice-wrap">
      <StatusBar stepIdx={0}/>
      <div className="choice-hero stagger">
        <h1 className="serif" style={{ animationDelay:'.05s'}}>Welcome.</h1>
        <p style={{ animationDelay:'.15s'}}>Let's get you checked in. This kiosk will guide you through every step.</p>
      </div>
      <div className="choice-grid stagger">
        <div className="choice-card" style={{ animationDelay:'.2s' }} onClick={onReturning}>
          <div className="pict a">
            {/* abstract patient illustration: simple gradient + glyph */}
            <svg viewBox="0 0 200 120" width="80%" height="80%" preserveAspectRatio="xMidYMid meet">
              <circle cx="100" cy="50" r="22" fill="none" stroke="var(--accent)" strokeWidth="2"/>
              <path d="M55 110c5-22 25-34 45-34s40 12 45 34" fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round"/>
              <circle cx="160" cy="30" r="4" fill="var(--accent)"/>
              <circle cx="160" cy="30" r="9" fill="none" stroke="var(--accent)" strokeWidth="1"/>
            </svg>
          </div>
          <div>
            <h3>I've been here before</h3>
            <p>Sign in with your phone number — we'll pull up your record.</p>
          </div>
          <div className="cta">Continue <span className="arrow"><svg width="18" 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></span></div>
        </div>
        <div className="choice-card" style={{ animationDelay:'.3s' }} onClick={onNew}>
          <div className="pict b">
            <svg viewBox="0 0 200 120" width="80%" height="80%" preserveAspectRatio="xMidYMid meet">
              <circle cx="100" cy="50" r="22" fill="none" stroke="#B9711F" strokeWidth="2"/>
              <path d="M55 110c5-22 25-34 45-34s40 12 45 34" fill="none" stroke="#B9711F" strokeWidth="2" strokeLinecap="round"/>
              <path d="M100 30v14M93 37h14" stroke="#B9711F" strokeWidth="2" strokeLinecap="round"/>
            </svg>
          </div>
          <div>
            <h3>First time here</h3>
            <p>Takes about 90 seconds — your name, phone, and a couple of details.</p>
          </div>
          <div className="cta">Get set up <span className="arrow"><svg width="18" 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></span></div>
        </div>
      </div>
    </div>
  );
}

// ── 3. SIGN IN (keypad) ────────────────────────────────────
function SignInScreen({ onAuthed, onBack }) {
  const [digits, setDigits] = useStateA('98765');
  const max = 10;
  const push = (d) => setDigits(s => (s.length >= max ? s : s + d));
  const back = () => setDigits(s => s.slice(0, -1));
  const clear = () => setDigits('');
  const formatted = digits.padEnd(10, ' ').replace(/(.{5})/, '$1 ');
  const ready = digits.length === 10;
  return (
    <div className="signin">
      <StatusBar stepIdx={0}/>
      <div>
        <h1>What's your phone number?</h1>
        <p>We'll find your record and skip the small talk.</p>
        <div className="phone-display">
          <span className="cc">+91</span>
          <span>
            {formatted.split('').map((ch, i) => (
              ch === ' '
                ? <span key={i} style={{ display:'inline-block', width: 12 }} />
                : <span key={i} className="digit" style={{ color: ch.trim() ? 'var(--ink)' : 'var(--muted)' }}>
                    {ch.trim() || '_'}
                  </span>
            ))}
          </span>
          <span className="caret" />
        </div>
        <div className="signin-actions">
          <button className="btn-secondary" onClick={onBack}>← Back</button>
          <button className={`btn-primary accent`} disabled={!ready}
            style={{ opacity: ready ? 1 : .4, cursor: ready ? 'pointer' : 'not-allowed' }}
            onClick={() => ready && onAuthed({ name: 'Priya', phone: digits })}>
            Continue
            <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="keypad">
        {[1,2,3,4,5,6,7,8,9].map(n => <button key={n} onClick={() => push(String(n))}>{n}</button>)}
        <button className="action" onClick={clear}>Clear</button>
        <button onClick={() => push('0')}>0</button>
        <button className="action" onClick={back}>← Back</button>
      </div>
    </div>
  );
}

// ── 4. REGISTER ────────────────────────────────────────────
const REG_STEPS = [
  { key:'name',  q:"What's your name?",       placeholder:'First name',     kb:'alpha' },
  { key:'phone', q:"And your phone number?",  placeholder:'10 digits',      kb:'num'   },
  { key:'place', q:"Which area do you live in?", placeholder:'e.g. Bandra W', kb:'alpha' },
  { key:'age',   q:"How old are you?",        placeholder:'Years',          kb:'num'   },
];

const KB_ROWS_A = [
  ['Q','W','E','R','T','Y','U','I','O','P'],
  ['A','S','D','F','G','H','J','K','L'],
  ['Z','X','C','V','B','N','M'],
];

function OnScreenKeyboard({ onKey, onBack, onDone, kb = 'alpha' }) {
  if (kb === 'num') {
    return (
      <div className="kb" style={{ maxWidth: 480, margin: '0 auto', left:'auto', right:'auto', position:'absolute', bottom: 56, left:'50%', transform:'translateX(-50%)' }}>
        <div className="kb-row">{[1,2,3].map(n => <button key={n} className="kb-key" onClick={() => onKey(String(n))}>{n}</button>)}</div>
        <div className="kb-row">{[4,5,6].map(n => <button key={n} className="kb-key" onClick={() => onKey(String(n))}>{n}</button>)}</div>
        <div className="kb-row">{[7,8,9].map(n => <button key={n} className="kb-key" onClick={() => onKey(String(n))}>{n}</button>)}</div>
        <div className="kb-row">
          <button className="kb-key" onClick={onBack}>←</button>
          <button className="kb-key" onClick={() => onKey('0')}>0</button>
          <button className="kb-key action" onClick={onDone}>Done</button>
        </div>
      </div>
    );
  }
  return (
    <div className="kb">
      {KB_ROWS_A.map((row, i) => (
        <div className="kb-row" key={i}>
          {row.map(ch => (
            <button key={ch} className="kb-key" onClick={() => onKey(ch.toLowerCase())}>{ch}</button>
          ))}
          {i === 2 && <button className="kb-key wide" onClick={onBack}>←</button>}
        </div>
      ))}
      <div className="kb-row">
        <button className="kb-key" onClick={() => onKey(' ')} style={{ flex: 4 }}>Space</button>
        <button className="kb-key action" onClick={onDone}>Done</button>
      </div>
    </div>
  );
}

function RegisterScreen({ onDone, onBack }) {
  const [i, setI] = useStateA(0);
  const [data, setData] = useStateA({});
  const step = REG_STEPS[i];
  const value = data[step.key] || '';
  const focused = true;

  const push = (ch) => setData(d => ({ ...d, [step.key]: (d[step.key] || '') + ch }));
  const back = () => setData(d => ({ ...d, [step.key]: (d[step.key] || '').slice(0, -1) }));
  const next = () => {
    if (i < REG_STEPS.length - 1) setI(i + 1);
    else onDone({ name: data.name || 'Friend', ...data });
  };

  return (
    <div className="register">
      <StatusBar stepIdx={0}/>
      <div className="reg-progress">
        {REG_STEPS.map((s, idx) => (
          <i key={s.key} className={idx < i ? 'done' : idx === i ? 'cur' : ''} />
        ))}
      </div>
      <h1 key={i} style={{ animation: 'swapIn .5s var(--ease-out)' }}>{step.q}</h1>
      <p className="sub">Step {i+1} of {REG_STEPS.length}.  We'll only ask once.</p>
      <div className={`reg-field ${focused ? 'focused' : ''}`} style={{ textTransform: step.kb === 'alpha' ? 'capitalize' : 'none' }}>
        {value
          ? <span>{value}<span className="caret" style={{ display:'inline-block', width: 2, height: 32, marginLeft: 6, verticalAlign: 'middle', background: 'var(--accent)'}}/></span>
          : <span className="placeholder">{step.placeholder}</span>}
      </div>
      <div className="reg-foot">
        <button className="btn-secondary" onClick={i === 0 ? onBack : () => setI(i-1)}>← Back</button>
        <button className="btn-primary accent" onClick={next}
                style={{ opacity: value ? 1 : .4, pointerEvents: value ? 'auto' : 'none' }}>
          {i === REG_STEPS.length - 1 ? 'Finish' : 'Next'}
          <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>
      <OnScreenKeyboard kb={step.kb} onKey={push} onBack={back} onDone={next}/>
    </div>
  );
}

// ── 5. WELCOME BRIEFING ────────────────────────────────────
function WelcomeScreen({ name = 'Priya', onBegin, onBack }) {
  return (
    <div className="welcome">
      <StatusBar stepIdx={0}/>
      <div className="stagger" style={{ display:'flex', flexDirection:'column', gap: 18 }}>
        <h1 style={{ animationDelay:'.05s' }}>Hi <em>{name}.</em></h1>
        <p className="lede" style={{ animationDelay:'.15s'}}>
          Here's what we'll do today. Take your time — the kiosk waits for you, not the other way around.
        </p>
      </div>
      <div className="step-grid stagger">
        {[
          { n:'01', t:'A few questions',  d:'About your routine and how your mouth feels.', meta:'12 items', time:'90 sec' },
          { n:'02', t:'Photos of your mouth', d:'The scan guide walks through 13 angles. Just follow along.', meta:'13 photos', time:'4 min' },
          { n:'03', t:'Your voice',         d:'Twenty seconds of you opening and closing your mouth.', meta:'20 sec', time:'20 sec' },
          { n:'04', t:'A breath sample',    d:'Exhale slowly into the port — checks for H₂S levels.', meta:'8 sec', time:'10 sec' },
        ].map((s, i) => (
          <div key={i} className="step-card" style={{ animationDelay: `${0.2 + i * .07}s` }}>
            <div className="step-num">{s.n}</div>
            <div>
              <h4>{s.t}</h4>
              <p style={{ margin: '8px 0 0', color: 'var(--ink-3)', fontSize: 14, lineHeight: 1.5 }}>{s.d}</p>
            </div>
            <div className="meta"><span>{s.meta}</span><span>~ {s.time}</span></div>
          </div>
        ))}
      </div>
      <div className="welcome-foot">
        <button className="btn-secondary" onClick={onBack}>← Not me</button>
        <div className="row">
          <span className="total">Total · about <b>6 minutes</b></span>
          <button className="btn-primary accent" onClick={onBegin}>
            Let's begin
            <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>
  );
}

// ── 6. CONSENT ─────────────────────────────────────────────
function ConsentScreen({ onAgree, onBack }) {
  return (
    <div className="consent">
      <StatusBar stepIdx={0}/>
      <h1 className="serif" style={{ animation: 'rise .55s var(--ease-out) both' }}>
        Before we start.
      </h1>
      <p className="lede" style={{ animation: 'rise .6s var(--ease-out) .1s both' }}>
        We'll capture photos of the inside of your mouth, a short voice sample, and a breath reading.
        It's encrypted on the device and only your dentist can see it.
      </p>
      <div className="pillars stagger">
        {[
          { ic: 'shield',   t:'End-to-end encrypted',  d:'Data is sealed on the kiosk before it leaves — only your dentist holds the key.'},
          { ic: 'user',     t:'Only your dentist',     d:'No third parties. Not used for ads. Not shared without your explicit consent.'},
          { ic: 'flask',    t:'Yours to delete',       d:'Ask the front desk anytime to remove your records. Done within 24 hours.'},
        ].map((p, i) => {
          const Ic = I[p.ic] || I.shield;
          return (
            <div key={i} className="pillar" style={{ animationDelay: `${0.2 + i*0.08}s`}}>
              <span className="ico-wrap"><Ic size={22}/></span>
              <h4>{p.t}</h4>
              <p>{p.d}</p>
            </div>
          );
        })}
      </div>
      <div className="consent-foot">
        <div className="row" style={{ gap: 18 }}>
          <button className="btn-secondary" onClick={onBack}>← Back</button>
          <span className="link">Read privacy policy</span>
        </div>
        <button className="btn-primary accent" onClick={onAgree}>
          I agree — let's go
          <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, { IdleScreen, ChoiceScreen, SignInScreen, RegisterScreen, WelcomeScreen, ConsentScreen });
