/* Flow A — onboarding (A1..A5). Full-takeover screens — no app shell. */

function ScreenA1({ next }) {
  const langs = ['हिन्दी', 'मराठी', 'தமிழ்', 'తెలుగు', 'বাংলা', 'ಕನ್ನಡ', 'ଓଡ଼ିଆ', 'English'];
  const [picked, setPicked] = _us('हिन्दी');
  const [toast, setToast] = _us(null);
  const [speaking, setSpeaking] = _us(false);

  _ue(() => {
    setSpeaking(true);
    Voice.speak(DEMO.A1_WELCOME, {
      onEnd: () => setSpeaking(false),
      onError: () => setSpeaking(false),
    });
    return () => Voice.stopSpeaking();
  }, []);
  const onPick = (l) => {
    if (l === 'हिन्दी') setPicked(l);
    else { setToast(`${l} — Coming soon`); setTimeout(() => setToast(null), 1600); }
  };
  return (
    <div className="screen-in absolute inset-0 bg-white flex flex-col">
      <StatusBar/>
      {toast && (
        <div className="absolute top-14 left-1/2 -translate-x-1/2 z-40 toast-in">
          <div className="bg-ink-900 text-white text-[12px] font-medium px-3 py-1.5 rounded-full shadow-lift">{toast}</div>
        </div>
      )}
      <div className="flex-1 flex flex-col items-center justify-center px-6 text-center">
        <SarthiOrb size={132} listening={speaking}/>
        <div className="mt-10 text-[34px] font-bold leading-tight text-ink-900 deva">
          नमस्ते राजेश <span className="inline-block">👋</span>
        </div>
        <div className="mt-3 text-[17px] text-ink-700 deva max-w-[300px] leading-relaxed">
          Main hoon <span className="font-semibold">Sarthi</span> — aapka delivery partner co-pilot.
        </div>
        <div className="mt-2 text-[13px] text-ink-500 max-w-[300px] leading-relaxed">
          I'll help you start earning in the next 90 minutes.
        </div>

        <div className="mt-10 w-full">
          <div className="text-[11px] font-semibold text-ink-500 uppercase tracking-wider mb-3">Choose your language</div>
          <div className="flex flex-wrap gap-2 justify-center">
            {langs.map(l => {
              const on = l === picked;
              return (
                <button key={l} onClick={() => onPick(l)}
                  className={`px-3.5 py-1.5 rounded-full text-[13px] font-semibold press border transition deva
                    ${on ? 'bg-ink-900 text-white border-ink-900' : 'bg-white text-ink-700 border-ink-200 hover:bg-ink-50'}`}>
                  {l}
                </button>
              );
            })}
          </div>
        </div>
      </div>
      <div className="px-5 pb-8 pt-3">
        <button onClick={next}
                className="guide-a1-cta w-full h-14 rounded-2xl text-white font-semibold text-[16px] press orb-grad shadow-orb deva flex items-center justify-center gap-2">
          Chalo shuru karte hain
          <ArrowR size={18} stroke="#fff"/>
        </button>
      </div>
    </div>
  );
}

function ScreenA2({ next }) {
  const [license, setLicense] = _us(false);
  const [aadhaar, setAadhaar] = _us(false);
  const ready = license && aadhaar;
  const bubble = !license
    ? { hi: 'Pehle license dikhao, sirf face up rakhna.', en: 'First show your license, keep it face up.', tts: DEMO.A2_LICENSE }
    : !aadhaar
    ? { hi: 'Shabaash! Ab Aadhaar dikhao.',                en: 'Well done! Now show your Aadhaar.', tts: DEMO.A2_AADHAAR }
    : { hi: 'Sab ho gaya. Aage badhte hain.',              en: 'All done. Let’s continue.', tts: DEMO.A2_DONE };

  _ue(() => {
    Voice.speak(bubble.tts, { onError: () => {} });
    return () => Voice.stopSpeaking();
  }, [bubble.tts]);

  const UploadCard = ({ label, sub, done, onTap }) => (
    <button onClick={onTap} disabled={done}
      className={`w-full text-left rounded-2xl border-2 border-dashed p-4 press transition flex items-center gap-3
        ${done ? 'bg-pace-50 border-pace-200' : 'bg-white border-ink-200 hover:border-ink-300'}`}>
      <div className={`w-12 h-12 rounded-xl grid place-items-center shrink-0
        ${done ? 'bg-pace-500 text-white' : 'bg-ink-100 text-ink-700'}`}>
        {done ? <Check size={22} stroke="#fff" sw={2.5}/> : <Camera size={22}/>}
      </div>
      <div className="flex-1">
        <div className="text-[14px] font-semibold text-ink-900">{label}</div>
        <div className="text-[12px] text-ink-500 mt-0.5">{done ? '✓ Scanned successfully' : sub}</div>
      </div>
      {!done && <ChevR size={18} stroke="#94A3B8"/>}
    </button>
  );

  return (
    <div className="screen-in absolute inset-0 bg-white flex flex-col">
      <StatusBar/>
      {/* Sarthi mini-header */}
      <div className="px-5 pt-2 pb-4">
        <div className="flex items-start gap-3">
          <SarthiOrb size={36}/>
          <div className="flex-1 bg-sarthi-50 border border-sarthi-100 rounded-2xl rounded-tl-sm px-3.5 py-2.5">
            <div className="text-[14px] font-semibold text-ink-900 deva">{bubble.hi}</div>
            <div className="text-[11px] text-ink-500 mt-0.5">{bubble.en}</div>
          </div>
        </div>
      </div>

      <div className="px-5 pb-4">
        <div className="text-[12px] font-semibold text-ink-500 uppercase tracking-wider mb-1">Step 1 of 4</div>
        <div className="text-[22px] font-bold text-ink-900 tracking-tight">Upload your documents</div>
        <div className="text-[13px] text-ink-500 mt-1">Sarthi reviews each scan instantly — usually under 8 seconds.</div>
      </div>

      <div className="px-5 space-y-3">
        <UploadCard label="Driving License"
                    sub="Tap to scan front side"
                    done={license}
                    onTap={() => setLicense(true)}/>
        <UploadCard label="Aadhaar Card"
                    sub="Tap to scan front side"
                    done={aadhaar}
                    onTap={() => setAadhaar(true)}/>

        <div className="mt-2 flex items-center gap-2 text-[11px] text-ink-500">
          <ShieldOk size={14} stroke="#059669"/>
          <span>Your documents are encrypted and stored securely.</span>
        </div>
      </div>

      <div className="flex-1"/>
      <div className="px-5 pb-8 pt-4">
        <button onClick={ready ? next : null} disabled={!ready}
          className={`w-full h-14 rounded-2xl font-semibold text-[16px] press flex items-center justify-center gap-2
            ${ready ? 'orb-grad text-white shadow-orb' : 'bg-ink-100 text-ink-300'}`}>
          Continue
          {ready && <ArrowR size={18} stroke="#fff"/>}
        </button>
      </div>
    </div>
  );
}

const SCENARIOS = [
  {
    badge: 'Restaurant delay',
    hi: 'Kalpana karo: tum restaurant pahunche, lekin order ready nahi hai. Restaurant wala bol raha hai "10 minute aur lagega." Tum kya karoge?',
    en: 'Imagine: you reach the restaurant but the order isn\'t ready. The owner says it\'ll take 10 more minutes. What will you do?',
    correct: 'c',
    opts: [
      { id: 'a', hi: '10 minute wait karoonga, kuch nahi karoonga',                   en: 'I\'ll just wait 10 minutes, do nothing' },
      { id: 'b', hi: 'Cancel kar doonga, time waste hoga',                            en: 'I\'ll cancel — it\'s a waste of time' },
      { id: 'c', hi: 'App pe "restaurant delay" button daboonga, escalate karoonga', en: 'I\'ll press "restaurant delay" to escalate' },
    ],
    right: { hi: 'Bilkul sahi! Yahi top 10% partners karte hain.', en: 'Exactly! This is what top 10% partners do.' },
    wrong: { hi: 'Theek hai, lekin aur bhi achha tareeka hai. Sahi answer hai option (c).', en: 'Okay — but there\'s a better way. The right answer is option (c).' },
  },
  {
    badge: 'Difficult customer',
    hi: 'Customer phone pe gussa hai, kah raha hai "tu late kyun hai? Tip nahi doonga." Tumhara pehla reaction kya hoga?',
    en: 'The customer is angry on the phone, saying "Why are you late? No tip for you." What\'s your first reaction?',
    correct: 'b',
    opts: [
      { id: 'a', hi: 'Wahi tone mein wapas baat karoonga',                            en: 'I\'ll match the same tone back' },
      { id: 'b', hi: 'Shaant raho, "Sorry sir, traffic mein tha" bolo, address confirm karo', en: 'Stay calm, "Sorry sir, I was in traffic", confirm the address' },
      { id: 'c', hi: 'Order cancel kar ke nikal jaoonga',                              en: 'I\'ll just cancel and leave' },
    ],
    right: { hi: 'Sahi! Shaant rehna sabse important hai. Sarthi gaali sune toh incident file karega.', en: 'Right! Staying calm matters most. If Sarthi detects abuse, it\'ll auto-file the incident.' },
    wrong: { hi: 'Pehle shaant raho. Sarthi tumhe gussa customers ke saath baat karna sikhayega.', en: 'Stay calm first. Sarthi will teach you how to handle angry customers.' },
  },
  {
    badge: 'Wrong address',
    hi: 'GPS galat jagah le aaya hai. Customer phone nahi utha raha. Tum kya karoge?',
    en: 'GPS led you to the wrong place. Customer isn\'t picking up. What will you do?',
    correct: 'a',
    opts: [
      { id: 'a', hi: 'Sarthi button daba ke "address galat" bolo — Sarthi customer ko call karega', en: 'Press Sarthi and say "wrong address" — Sarthi will call the customer' },
      { id: 'b', hi: 'Khud customer ko 5–6 baar call karoonga',                                       en: 'Call the customer 5–6 times myself' },
      { id: 'c', hi: 'Wahi rakh ke nikal jaoonga, "delivered" mark karoonga',                         en: 'Drop the order there and mark as delivered' },
    ],
    right: { hi: 'Bilkul. Sarthi customer ko call karega aur correct location nikalega. Tumhara time bachega.', en: 'Exactly. Sarthi will call the customer and extract the correct location, saving your time.' },
    wrong: { hi: 'Apna time mat barbaad karo. Sarthi se boln, woh customer se confirm karke address theek karega.', en: 'Don\'t waste your time. Tell Sarthi — it\'ll confirm and fix the address for you.' },
  },
];

function ScreenA3({ idx, results, onAnswer, onNext }) {
  const sc = SCENARIOS[idx];
  const [picked, setPicked] = _us(null);
  const ttsSc = SCENARIO_TTS[idx];

  _ue(() => { setPicked(null); }, [idx]);

  _ue(() => {
    const preload = [ttsSc?.question, ttsSc?.explainRight, ttsSc?.explainWrong].filter(Boolean);
    if (preload.length) Voice.preload(preload);
    if (ttsSc?.question) Voice.speak(ttsSc.question, { onError: () => {} });
    return () => Voice.stopSpeaking();
  }, [idx]);

  const isRight = picked === sc.correct;
  const feedback = picked && (isRight ? sc.right : sc.wrong);

  const handlePick = (id) => {
    if (picked) return;
    setPicked(id);
    const correct = id === sc.correct;
    onAnswer({ scenario: idx, picked: id, correct });
    const explain = correct
      ? (ttsSc?.explainRight || sc.right.hi)
      : (ttsSc?.explainWrong || ttsSc?.explain || sc.wrong.hi);
    Voice.preload([explain]);
    Voice.speak(explain, { onError: () => {} });
  };

  return (
    <div className="screen-in absolute inset-0 bg-surface flex flex-col" key={idx}>
      <StatusBar/>
      <div className="px-5 pt-2 pb-3 flex items-center gap-3">
        <button type="button" aria-hidden="true" tabIndex={-1}
                className="w-9 h-9 rounded-full bg-white border border-ink-200 grid place-items-center opacity-40 pointer-events-none"><ChevL size={18}/></button>
        <div className="flex-1">
          <div className="text-[11px] font-semibold text-ink-500 uppercase tracking-wider">Step 2 of 4 — Real situations</div>
          <div className="text-[15px] font-bold text-ink-900">Scenario {idx + 1} of 3 · {sc.badge}</div>
        </div>
        <div className="flex items-center gap-1">
          {[0,1,2].map(i => (
            <span key={i} className={`h-2 rounded-full transition-all ${i === idx ? 'w-5 bg-ink-900' : i < idx ? 'w-2 bg-pace-500' : 'w-2 bg-ink-200'}`}></span>
          ))}
        </div>
      </div>

      <div className="px-5">
        <div className="guide-a3-sarthi bg-white border border-ink-200 rounded-2xl p-4 shadow-card">
          <div className="flex items-center gap-2">
            <SarthiOrb size={32}/>
            <div className="text-[13px] font-semibold text-sarthi-deep">Sarthi</div>
            <SpeakingDots color="#FC8019" size={12}/>
            <span className="ai-badge ml-auto px-2 py-0.5 rounded-full bg-sarthi-100 text-sarthi-deep text-[9px] font-bold uppercase tracking-wider">AI</span>
          </div>
          <div className="mt-3 text-[16px] leading-snug text-ink-900 font-semibold deva">{sc.hi}</div>
          <div className="mt-2 text-[12px] text-ink-500 leading-relaxed">{sc.en}</div>
        </div>
      </div>

      <div className="px-5 mt-4 space-y-2.5">
        {sc.opts.map(o => {
          const on = picked === o.id;
          const right = picked && o.id === sc.correct;
          const wrong = on && o.id !== sc.correct;
          return (
            <button key={o.id} onClick={() => handlePick(o.id)} disabled={!!picked}
              className={`w-full text-left rounded-2xl border p-3.5 press transition flex items-center gap-3
                ${right ? 'bg-pace-50 border-pace-500' :
                  wrong ? 'bg-rose-50 border-rose-300' :
                  on ? 'bg-ink-100 border-ink-300' : 'bg-white border-ink-200 hover:border-ink-300'}`}>
              <div className={`w-7 h-7 rounded-full grid place-items-center shrink-0 text-[12px] font-bold
                ${right ? 'bg-pace-500 text-white' :
                  wrong ? 'bg-rose-500 text-white' : 'bg-ink-100 text-ink-700'}`}>
                {right ? <Check size={14} stroke="#fff" sw={3}/> : wrong ? <X size={14} stroke="#fff" sw={3}/> : o.id.toUpperCase()}
              </div>
              <div className="flex-1">
                <div className="text-[13px] font-semibold text-ink-900 deva leading-snug">{o.hi}</div>
                <div className="text-[11px] text-ink-500 mt-0.5">{o.en}</div>
              </div>
            </button>
          );
        })}
      </div>

      {picked && (
        <div className="px-5 mt-3 fade-in">
          <div className={`rounded-2xl p-3.5 border flex gap-3 items-start
            ${isRight ? 'bg-pace-50 border-pace-200' : 'bg-sarthi-50 border-sarthi-100'}`}>
            <SarthiOrb size={32}/>
            <div className="flex-1">
              <div className="text-[13px] font-semibold text-ink-900 deva leading-snug">{feedback.hi}</div>
              <div className="text-[11px] text-ink-500 mt-0.5">{feedback.en}</div>
              <button type="button"
                onClick={() => {
                  const text = isRight
                    ? (ttsSc?.explainRight || DEMO.A3_EXPLAIN_RIGHT)
                    : (ttsSc?.explainWrong || DEMO.A3_EXPLAIN_WRONG);
                  Voice.preload([text]);
                  Voice.speak(text, { onError: () => {} });
                }}
                className="mt-2 text-[12px] font-semibold text-sarthi-deep flex items-center gap-1.5 press">
                <Play size={11} stroke="#FC8019" fill="#FC8019"/> Listen to full explanation
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="flex-1"/>
      <div className="px-5 pb-8 pt-4">
        <button onClick={picked ? onNext : null} disabled={!picked}
          className={`w-full h-14 rounded-2xl font-semibold text-[16px] press flex items-center justify-center gap-2
            ${picked ? 'orb-grad text-white shadow-orb' : 'bg-ink-100 text-ink-300'}`}>
          {idx < 2 ? 'Next scenario' : 'See my training summary'}
          {picked && <ArrowR size={18} stroke="#fff"/>}
        </button>
      </div>
    </div>
  );
}

function ScreenA4({ next, results = [] }) {
  _ue(() => {
    Voice.speak(DEMO.A4_COMPLETE, { onError: () => {} });
    return () => Voice.stopSpeaking();
  }, []);

  const rows = [
    { hi: 'Restaurant delay handle karna',       en: 'Handle restaurant delays' },
    { hi: 'Mushkil customer ke saath baat karna', en: 'Talk to a difficult customer' },
    { hi: 'Wrong address pe order pahunchana',   en: 'Reach a wrong address' },
  ];
  const correctCount = results.filter(r => r.correct).length;
  return (
    <div className="screen-in absolute inset-0 bg-surface flex flex-col">
      <StatusBar/>
      <div className="px-5 pt-4 pb-2">
        <div className="text-[11px] font-semibold text-ink-500 uppercase tracking-wider">Step 3 of 4</div>
        <div className="text-[22px] font-bold text-ink-900 tracking-tight">Training complete</div>
      </div>

      <div className="px-5 mt-3">
        <div className="bg-white rounded-2xl border border-ink-200 p-5 shadow-card">
          <div className="flex items-center gap-3">
            <div className="relative">
              <SarthiOrb size={56}/>
              <div className="absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-pace-500 grid place-items-center ring-2 ring-white">
                <Check size={14} stroke="#fff" sw={3}/>
              </div>
            </div>
            <div>
              <div className="text-[22px] font-extrabold text-ink-900 tracking-tight tabular-nums">{correctCount} / 3</div>
              <div className="text-[12px] text-ink-500 deva">
                {correctCount === 3 ? 'Aapne sab sahi jawaab diye' : correctCount >= 1 ? 'Achha kiya — practice karte raho' : 'Sarthi tumhe sab seekhayega'}
              </div>
            </div>
          </div>

          <div className="mt-4 space-y-2">
            {rows.map((r, i) => {
              const res = results[i];
              const ok = res?.correct;
              return (
                <div key={i} className="flex items-center gap-3 py-2 border-t border-ink-100">
                  <div className={`w-6 h-6 rounded-full grid place-items-center pop-in ${ok ? 'bg-pace-100' : res ? 'bg-rose-100' : 'bg-ink-100'}`}
                       style={{ animationDelay: `${i * 120}ms` }}>
                    {ok ? <Check size={14} stroke="#059669" sw={3}/> : res ? <X size={14} stroke="#E11D48" sw={3}/> : <Check size={14} stroke="#94A3B8" sw={2}/>}
                  </div>
                  <div className="flex-1">
                    <div className="text-[13px] font-semibold text-ink-900 deva">{r.hi}</div>
                    <div className="text-[11px] text-ink-500">{r.en}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className="px-5 mt-4">
        <div className="rounded-2xl p-4 bg-gradient-to-br from-sarthi-50 via-white to-pace-50 border border-sarthi-100">
          <div className="flex items-start gap-3">
            <SarthiOrb size={36}/>
            <div>
              <div className="text-[14px] font-semibold text-ink-900 deva leading-snug">
                Aapki training complete hai. Sarthi hamesha aapke saath rahega — bas niche ka button daba ke baat karo.
              </div>
              <div className="text-[11px] text-ink-500 mt-1">
                Your training is complete. Sarthi is always with you — just press the button below to talk anytime.
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="flex-1"/>
      <div className="px-5 pb-8 pt-4">
        <button onClick={next}
          className="w-full h-14 rounded-2xl orb-grad text-white font-semibold text-[16px] press shadow-orb flex items-center justify-center gap-2">
          Next: Choose your first shift
          <ArrowR size={18} stroke="#fff"/>
        </button>
      </div>
    </div>
  );
}

function ScreenA5({ next }) {
  _ue(() => {
    Voice.speak(DEMO.A5_CONGRATS, { onError: () => {} });
    return () => Voice.stopSpeaking();
  }, []);

  const shifts = [
    { day: 'Today',    time: '6:00 PM – 10:00 PM', zone: 'Hadapsar',     orders: '~7–9 orders', bonus: '+₹120 surge', hot: true  },
    { day: 'Tomorrow', time: '10:00 AM – 2:00 PM', zone: 'Viman Nagar',  orders: '~8–10 orders', bonus: null,         hot: false },
    { day: 'Tomorrow', time: '7:00 PM – 11:00 PM', zone: 'Koregaon Park', orders: '~10–12 orders', bonus: '+₹80 night',  hot: true  },
  ];
  const [picked, setPicked] = _us(null);
  return (
    <div className="screen-in absolute inset-0 bg-white flex flex-col overflow-hidden">
      <StatusBar/>
      <Confetti/>
      <div className="px-5 pt-6 text-center">
        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-pace-50 border border-pace-100">
          <span className="text-pace-700 text-[11px] font-semibold uppercase tracking-wider">Welcome</span>
        </div>
        <div className="mt-3 text-[28px] font-extrabold text-ink-900 tracking-tight leading-tight">
          Welcome to Swiggy, Rajesh 🎉
        </div>
        <div className="text-[13px] text-ink-500 mt-1 deva max-w-[300px] mx-auto">
          Aapka pehla shift kab le sakte ho?
        </div>
      </div>

      <div className="px-5 mt-5 space-y-2.5 relative z-20">
        {shifts.map((s, i) => {
          const on = picked === i;
          return (
            <button key={i} onClick={() => setPicked(i)}
              className={`w-full text-left rounded-2xl p-3.5 border press transition
                ${on ? 'bg-ink-900 text-white border-ink-900' : 'bg-white border-ink-200 hover:border-ink-300'}`}>
              <div className="flex items-center gap-3">
                <div className={`w-12 h-12 rounded-xl grid place-items-center shrink-0
                  ${on ? 'bg-white/10' : 'bg-pace-50'}`}>
                  <Clock size={20} stroke={on ? '#fff' : '#059669'}/>
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-1.5">
                    <div className={`text-[14px] font-bold ${on ? 'text-white' : 'text-ink-900'}`}>{s.day} · {s.time}</div>
                    {s.hot && <Flame size={13} stroke={on ? '#FBBF24' : '#F59E0B'}/>}
                  </div>
                  <div className={`text-[11px] mt-0.5 ${on ? 'text-white/70' : 'text-ink-500'}`}>
                    {s.zone} · {s.orders}{s.bonus ? ` · ${s.bonus}` : ''}
                  </div>
                </div>
                {on && <CheckCirc size={22} stroke="#10B981"/>}
              </div>
            </button>
          );
        })}
      </div>

      <div className="flex-1"/>
      <div className="px-5 pb-8 pt-4 relative z-20">
        <button onClick={picked != null ? next : null} disabled={picked == null}
          className={`w-full h-14 rounded-2xl font-semibold text-[16px] press flex items-center justify-center gap-2
            ${picked != null ? 'orb-grad text-white shadow-orb' : 'bg-ink-100 text-ink-300'}`}>
          Confirm shift &amp; go online
          {picked != null && <ArrowR size={18} stroke="#fff"/>}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenA1, ScreenA2, ScreenA3, ScreenA4, ScreenA5 });
