/* Flow B — crisis hero: hold-to-speak, STT prompt, TTS response, intelligent actions. */

const B3_ACTIONS = [
  { hi: 'Restaurant manager notified', en: '' },
  { hi: 'Customer ko delay SMS', en: '' },
  { hi: 'Rating safe — no penalty', en: '' },
];

function ScreenB1({ onSarthiHoldStart, showFabLabel, holding, orderState = 'picked', setOrderState = () => {}, guideFab }) {
  const delivered = orderState === 'delivered';
  return (
    <div className="screen-in absolute inset-0 bg-surface flex flex-col">
      <StatusBar/>
      <TopHeader name="Rajesh"/>

      <div className="flex-1 overflow-y-auto no-scrollbar px-4 pt-4 pb-28">
        <div className="rounded-2xl bg-white border border-ink-200 shadow-card overflow-hidden">
          <div className="px-4 pt-4 pb-3 flex items-center gap-2">
            <span className={`w-1.5 h-1.5 rounded-full shrink-0 ${delivered ? 'bg-ink-300' : 'bg-sw-orange animate-pulse'}`}></span>
            <span className={`text-[10px] font-bold uppercase tracking-wider whitespace-nowrap ${delivered ? 'text-ink-500' : 'text-sw-orange-dark'}`}>
              {delivered ? 'Delivered · #PD-48217' : 'Active · #PD-48217'}
            </span>
            <div className="ml-auto text-[11px] font-medium whitespace-nowrap">
              {delivered ? <span className="text-sw-orange-dark font-bold">+₹62 earned</span> : <span className="text-ink-500">ETA 8 min</span>}
            </div>
          </div>

          <div className="mx-4 rounded-xl overflow-hidden relative h-32 map-shimmer border border-orange-100">
            <svg viewBox="0 0 320 128" className="absolute inset-0 w-full h-full">
              <path d="M30 100 Q 90 50 160 60 T 290 30" stroke="#FC8019" strokeWidth="3.5" fill="none" strokeDasharray="6 4"/>
              <circle cx="30" cy="100" r="6" fill="#fff" stroke="#FC8019" strokeWidth="2.5"/>
              <g transform="translate(280 22)"><circle r="11" fill="#FC8019"/></g>
            </svg>
            <div className="absolute bottom-2 left-2 px-2 py-1 bg-white/90 backdrop-blur rounded-md text-[10px] font-semibold text-ink-700 flex items-center gap-1">
              <MapPin size={10} stroke="#FC8019"/> 2.1 km
            </div>
          </div>

          <div className="px-4 pt-3 pb-4">
            <div className="flex items-center gap-3">
              <div className="w-11 h-11 rounded-xl bg-amber-100 grid place-items-center text-[18px]">🍛</div>
              <div className="flex-1 min-w-0">
                <div className="text-[14px] font-bold text-ink-900 truncate">Punjabi Tadka</div>
                <div className="text-[11px] text-ink-500 truncate">1× Butter Chicken · 2× Naan · 1× Lassi</div>
              </div>
            </div>
            <div className="my-3 flex items-center gap-2">
              <div className="flex-1 border-t border-dashed border-ink-200"></div>
              <div className="w-7 h-7 rounded-full bg-ink-100 grid place-items-center"><ArrowR size={14}/></div>
              <div className="flex-1 border-t border-dashed border-ink-200"></div>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-11 h-11 rounded-xl bg-sky-100 grid place-items-center font-bold text-sky-700">PM</div>
              <div className="flex-1 min-w-0">
                <div className="text-[14px] font-bold text-ink-900">Priya M.</div>
                <div className="text-[11px] text-ink-500 truncate">Flat 304, Hadapsar Green Apts.</div>
              </div>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3 mt-3">
          <div className="rounded-2xl bg-white border border-ink-200 p-3 shadow-card">
            <div className="text-[10px] font-semibold text-ink-500 uppercase tracking-wider">Today</div>
            <div className="text-[22px] font-extrabold text-ink-900 tabular-nums mt-0.5">₹487</div>
          </div>
          <div className="rounded-2xl bg-gradient-to-br from-orange-50 to-amber-50 border border-amber-200 p-3 shadow-card">
            <div className="text-[10px] font-semibold text-amber-700 uppercase tracking-wider">Streak</div>
            <div className="text-[22px] font-extrabold text-amber-900 tabular-nums">4 <span className="text-[14px]">days 🔥</span></div>
          </div>
        </div>
      </div>

      <div className={guideFab ? 'guide-sarthi-fab' : ''}>
        <SarthiFAB onHoldStart={onSarthiHoldStart} showLabel={showFabLabel} holding={holding}/>
      </div>
      <BottomNav active="home"/>
    </div>
  );
}

function ScreenB2Overlay({ b2, onCancel }) {
  const { status, words = [], wordCount = 0, thinking, barLevels = [] } = b2;
  const phase = status === 'recording' ? 'recording' : status === 'processing' ? 'processing' : 'ready';
  const showTranscript = status === 'transcript' || status === 'thinking';

  return (
    <div className="absolute inset-0 z-40 flex flex-col" style={{ background: 'rgba(8, 5, 18, 0.88)', backdropFilter: 'blur(12px)' }}>
      <B2SpeakPrompt visible={status !== 'transcript' && status !== 'thinking'} phase={phase}/>

      <div className="flex-1 flex flex-col items-center justify-center px-6 pt-32 pb-8">
        <SarthiOrb size={130} listening glow/>

        <div className="mt-8 flex items-end justify-center gap-1.5 h-14">
          {[0,1,2,3,4,5,6].map(i => {
            const level = barLevels[i] ?? (status === 'recording' ? 0.35 : 0.2);
            return (
              <div key={i} className="rounded-full transition-all duration-75"
                   style={{ width: 6, height: 12 + level * 44,
                     background: 'linear-gradient(180deg, #FFB07A, #FC8019)' }}/>
            );
          })}
        </div>

        {showTranscript && words.length > 0 && (
          <div className="mt-6 max-w-[300px] rounded-2xl bg-white/10 border border-white/20 p-4 text-center">
            <div className="text-[10px] font-bold text-orange-200 uppercase tracking-wider mb-2">Aapne kaha:</div>
            <div className="text-white text-[17px] leading-snug font-semibold deva">
              {words.map((w, i) => (
                <span key={i} className={`inline-block mr-1 ${i < wordCount ? 'word-in' : 'opacity-30'}`}>{w}</span>
              ))}
            </div>
          </div>
        )}

        <div className="mt-6 flex items-center gap-2 text-white/75 text-[12px] font-medium deva">
          {thinking ? (
            <><SpeakingDots color="#FFB07A" size={14}/><span>Sarthi soch raha hai…</span></>
          ) : status === 'recording' ? (
            <><span className="w-2 h-2 rounded-full bg-orange-400 animate-pulse"/><span>Sun raha hoon — chhodne par jawab</span></>
          ) : status === 'processing' ? (
            <span>Transcript bhej rahe hain…</span>
          ) : (
            <span>Mic on — demo line bolo</span>
          )}
        </div>
      </div>

      <div className="pb-8 flex justify-center">
        <button onClick={onCancel}
          className="px-5 py-2 rounded-full bg-white/10 text-white text-[13px] font-semibold border border-white/20 press">
          Cancel
        </button>
      </div>
    </div>
  );
}

function ScreenB3Sheet({ onDismiss, onGuideDone }) {
  const [voicePhase, setVoicePhase] = _us('loading');
  const [actionsVisible, setActionsVisible] = _us(0);
  const [showActions, setShowActions] = _us(false);

  const speaking = voicePhase === 'speaking';
  const loading = voicePhase === 'loading';

  _ue(() => Voice.subscribe(({ phase }) => setVoicePhase(phase)), []);

  _ue(() => {
    setActionsVisible(0);
    setShowActions(false);

    const t = setTimeout(() => {
      Voice.speak(DEMO.B3_SPEECH, {
        onEnd: () => setShowActions(true),
        onError: () => setShowActions(true),
      });
    }, 120);

    return () => { clearTimeout(t); Voice.stopSpeaking(); };
  }, []);

  _ue(() => {
    if (!showActions) return;
    let i = 0;
    const t = setInterval(() => {
      i += 1;
      setActionsVisible(i);
      if (i >= B3_ACTIONS.length) clearInterval(t);
    }, 650);
    return () => clearInterval(t);
  }, [showActions]);

  return (
    <div className="absolute inset-0 z-40 flex flex-col justify-end"
         style={{ background: 'rgba(8, 5, 18, 0.75)', backdropFilter: 'blur(8px)' }}>
      <div className="sheet-in rounded-t-[28px] bg-white px-5 pt-5 pb-7 shadow-lift max-h-[92%] overflow-y-auto no-scrollbar">
        <div className="absolute left-1/2 -translate-x-1/2 top-2 w-10 h-1.5 rounded-full bg-ink-200"></div>

        <div className="mt-2 flex items-center gap-2.5">
          <SarthiOrb size={36}/>
          <div className="flex-1">
            <div className="flex items-center gap-1.5">
              <span className="text-[14px] font-bold text-sarthi-deep">Sarthi</span>
              <SpeakingDots color="#FC8019" size={11}/>
            </div>
            <div className="text-[10px] text-ink-500 uppercase tracking-wider font-semibold">
              {loading ? 'Taiyaar ho raha hai…' : speaking ? 'Bol raha hai…' : 'Intelligent response'}
            </div>
          </div>
          <button onClick={() => { Voice.stopSpeaking(); onDismiss(); }}
                  className="w-8 h-8 rounded-full bg-ink-100 grid place-items-center press">
            <X size={16}/>
          </button>
        </div>

        <div className="mt-4">
          <div className="text-[22px] font-extrabold text-ink-900 tracking-tight leading-tight deva">
            तेंशन मत लो, राजेश।
          </div>
        </div>

        <div className="mt-3 space-y-2">
          {[
            'Restaurant ko "order ready" dabao.',
            '5 min nahi toh escalate.',
            'Baaki Sarthi sambhalega.',
          ].map((line, i) => (
            <div key={i} className="rounded-xl bg-sarthi-50 border border-sarthi-100 px-3 py-2.5 flex gap-2.5 pop-in"
                 style={{ animationDelay: `${i * 80}ms` }}>
              <div className="w-5 h-5 rounded-full orb-grad grid place-items-center text-white text-[10px] font-bold shrink-0">{i + 1}</div>
              <div className="text-[13px] font-semibold text-ink-900 deva leading-snug">{line}</div>
            </div>
          ))}
        </div>

        <div className="mt-4 rounded-2xl bg-orange-50 border border-orange-200 p-3.5">
          <div className="flex items-center gap-2">
            <div className="w-6 h-6 rounded-full bg-sw-orange grid place-items-center">
              <Bolt size={13} stroke="#fff" sw={2.5} fill="#fff"/>
            </div>
            <div className="text-[12px] font-bold text-orange-900 uppercase tracking-wider">
              Sarthi ne aapke liye handle kiya
            </div>
          </div>
          {showActions ? (
            <AgentActionTimeline actions={B3_ACTIONS} visibleCount={actionsVisible}/>
          ) : (
            <div className="mt-2 flex items-center gap-2 text-[12px] text-orange-800">
              <SpeakingDots color="#FC8019" size={12}/>
              Coordinating…
            </div>
          )}
        </div>

        <button onClick={() => { Voice.stopSpeaking(); onDismiss(); onGuideDone?.(); }}
                className="mt-5 w-full h-14 rounded-2xl orb-grad text-white font-semibold text-[15px] press shadow-orb deva">
          Samajh gaya, dhanyavaad
        </button>
      </div>

    </div>
  );
}

Object.assign(window, { ScreenB1, ScreenB2Overlay, ScreenB3Sheet });
