/* HelpMe — AI Guide: Chat / Voice / Translate */

function GuideHeader({ onBack, status, mode, setMode }) {
  const tabs = [['chat', 'Chat', 'message-circle'], ['voice', 'Voice', 'mic'], ['translate', 'Translate', 'translate']];
  return (
    <div style={{ background: T.navy, paddingBottom: 12, flexShrink: 0 }}>
      <StatusBar light />
      <div style={{ padding: '2px 18px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="arrow-left" size={21} color="#fff" />
        </button>
        <div style={{ width: 46, height: 46, borderRadius: 999, background: '#fff', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <img src={LOGO} alt="GoWithMe AI Guide" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 18, color: '#fff' }}>GoWithMe AI Guide</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 7, height: 7, borderRadius: 9, background: '#5fd39a' }} />
            <span style={{ fontFamily: SANS, fontSize: 12.5, color: 'rgba(255,255,255,0.7)' }}>{status}</span>
          </div>
        </div>
        <button style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="phone" size={20} color="#fff" />
        </button>
      </div>
      <div style={{ display: 'flex', gap: 9, padding: '12px 18px 0' }}>
        {tabs.map(([id, label, icon]) => {
          const on = mode === id;
          return (
            <button key={id} onClick={() => setMode(id)} style={{
              flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, padding: '11px 0', borderRadius: 12, cursor: 'pointer',
              background: on ? '#fff' : 'rgba(255,255,255,0.08)', border: on ? 'none' : '1px solid rgba(255,255,255,0.16)',
              color: on ? T.navy : '#fff', fontFamily: SANS, fontWeight: 700, fontSize: 14.5,
            }}><Icon name={icon} size={18} color={on ? T.navy : '#fff'} />{label}</button>
          );
        })}
      </div>
    </div>
  );
}

function Bubble({ msg }) {
  const me = msg.from === 'me';
  return (
    <div style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start', marginBottom: 4 }}>
      <div style={{ maxWidth: '82%' }}>
        <div style={{
          background: me ? T.navy : T.white, color: me ? '#fff' : T.ink,
          padding: '13px 16px', borderRadius: 18, borderBottomRightRadius: me ? 5 : 18, borderBottomLeftRadius: me ? 18 : 5,
          fontFamily: SANS, fontSize: 15, lineHeight: 1.5, border: me ? 'none' : `1px solid ${T.line}`,
          boxShadow: me ? 'none' : '0 2px 8px rgba(16,40,66,0.04)', textWrap: 'pretty',
        }}>{msg.text}</div>
        {msg.time && <div style={{ fontFamily: SANS, fontSize: 11.5, color: T.muted, marginTop: 4, textAlign: me ? 'right' : 'left' }}>{msg.time}</div>}
      </div>
    </div>
  );
}

function Typing() {
  return (
    <div style={{ display: 'inline-flex', gap: 5, background: T.white, border: `1px solid ${T.line}`, padding: '14px 18px', borderRadius: 18, borderBottomLeftRadius: 5 }}>
      {[0, 1, 2].map(i => <span key={i} style={{ width: 8, height: 8, borderRadius: 9, background: T.muted, animation: 'blink 1.2s infinite', animationDelay: `${i * 0.18}s` }} />)}
    </div>
  );
}

function ChatMode({ onAction }) {
  const [msgs, setMsgs] = React.useState(HM.CHAT);
  const [typing, setTyping] = React.useState(false);
  const [text, setText] = React.useState('');
  const scroller = React.useRef(null);

  React.useEffect(() => { if (scroller.current) scroller.current.scrollTop = scroller.current.scrollHeight; }, [msgs, typing]);

  const reply = (q) => {
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      const low = q.toLowerCase();
      let r = "I can help with places, tickets, safety and local food. What would you like to explore?";
      if (low.includes('food') || low.includes('eat')) r = "For authentic Khmer food near you, try Khmer Kitchen or Marum. Both are verified and a short tuk-tuk away — fish amok is a must-try! 🍲";
      else if (low.includes('book') || low.includes('ticket')) { r = "I can book that through a verified APSARA seller right now. Tap below to start — no scam risk. 🎫"; }
      else if (low.includes('scam') || low.includes('safe')) r = "Scam Shield is active and blocked 2 threats today. Near Pub Street, avoid QR codes for payment unless the shop name matches. 🛡️";
      else if (low.includes('sunrise') || low.includes('time')) r = "Sunrise at Angkor Wat (5–7 AM) is unforgettable — the towers reflect in the moat. Want me to set an alarm and prep your audio guide?";
      setMsgs(m => [...m, { from: 'ai', text: r, time: '9:42 AM' }]);
    }, 1300);
  };
  const send = (q) => { if (!q.trim()) return; setMsgs(m => [...m, { from: 'me', text: q, time: '9:42 AM' }]); setText(''); reply(q); };

  return (
    <>
      <div ref={scroller} style={{ flex: 1, overflowY: 'auto', padding: '16px 18px 8px', background: T.cream }}>
        {msgs.map((m, i) => m.chips ? (
          <div key={i} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
            {m.chips.map(c => (
              <button key={c} onClick={() => { if (c.includes('Book')) onAction('book'); else if (c.includes('audio')) onAction('audio'); else send(c); }} style={{
                background: T.white, border: `1px solid ${T.line}`, borderRadius: 999, padding: '9px 15px', cursor: 'pointer',
                fontFamily: SANS, fontWeight: 600, fontSize: 13.5, color: T.navy,
              }}>{c}</button>
            ))}
          </div>
        ) : <Bubble key={i} msg={m} />)}
        {typing && <div style={{ marginBottom: 8 }}><Typing /></div>}
      </div>
      {/* input */}
      <div style={{ flexShrink: 0, padding: '12px 16px 18px', background: T.cream, borderTop: `1px solid ${T.line}`, display: 'flex', alignItems: 'center', gap: 10 }}>
        <button style={{ width: 44, height: 44, borderRadius: 999, background: T.white, border: `1px solid ${T.line}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="mic" size={20} color={T.navy} /></button>
        <input value={text} onChange={e => setText(e.target.value)} onKeyDown={e => e.key === 'Enter' && send(text)} placeholder="Ask your guide anything…" style={{
          flex: 1, height: 48, border: `1px solid ${T.line}`, borderRadius: 999, padding: '0 18px', outline: 'none', background: T.white, fontFamily: SANS, fontSize: 15, color: T.ink, minWidth: 0,
        }} />
        <button onClick={() => send(text)} style={{ width: 48, height: 48, borderRadius: 999, background: T.navy, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="send" size={20} color="#fff" /></button>
      </div>
    </>
  );
}

function VoiceMode() {
  const [listening, setListening] = React.useState(true);
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: T.cream }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px' }}>
        <Bubble msg={{ from: 'ai', text: "I'm listening. Speak in any language — English, French, Chinese, Korean, or Japanese! 🌏", time: '9:41 AM' }} />
        <Bubble msg={{ from: 'me', text: '🎙 Speaking…', time: '9:41 AM' }} />

        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '26px 0' }}>
          <div style={{ position: 'relative', width: 130, height: 130, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {listening && [0, 1, 2].map(i => (
              <div key={i} style={{ position: 'absolute', width: 130, height: 130, borderRadius: 999, border: `2px solid ${T.gold}`, animation: 'ripple 2s ease-out infinite', animationDelay: `${i * 0.6}s`, opacity: 0 }} />
            ))}
            <div style={{ width: 78, height: 78, borderRadius: 999, background: T.gold, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 10px 26px rgba(207,154,53,0.5)' }}>
              <Icon name="mic" size={32} color="#fff" />
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, height: 26, marginTop: 16 }}>
            {[14, 22, 10, 26, 12].map((h, i) => <div key={i} style={{ width: 4, height: h, borderRadius: 9, background: T.gold, animation: listening ? 'wave 0.6s ease-in-out infinite alternate' : 'none', animationDelay: `${i * 0.1}s` }} />)}
          </div>
          <div style={{ fontFamily: SANS, fontSize: 14, color: T.muted, marginTop: 12 }}>{listening ? 'Listening in English…' : 'Tap the mic to speak'}</div>
        </div>

        <Bubble msg={{ from: 'ai', text: 'I heard: "Where should I eat near Angkor Wat?" — here are top local spots within 1 km! 🍜', time: '9:41 AM' }} />
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 6 }}>
          {['Khmer Kitchen', 'Marum Restaurant', 'Pub Street'].map(c => (
            <button key={c} style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 999, padding: '9px 15px', cursor: 'pointer', fontFamily: SANS, fontWeight: 600, fontSize: 13.5, color: T.navy }}>{c}</button>
          ))}
        </div>
      </div>

      <div style={{ flexShrink: 0, padding: '16px 20px 22px', background: T.cream, borderTop: `1px solid ${T.line}`, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
          <button style={{ width: 50, height: 50, borderRadius: 999, background: T.white, border: `1px solid ${T.line}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="translate" size={22} color={T.body} /></button>
          <button onClick={() => setListening(!listening)} style={{ width: 72, height: 72, borderRadius: 999, background: listening ? T.danger : T.gold, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `0 10px 26px ${listening ? 'rgba(192,71,63,0.45)' : 'rgba(207,154,53,0.45)'}` }}>
            {listening ? <div style={{ width: 24, height: 24, borderRadius: 6, background: '#fff' }} /> : <Icon name="mic" size={30} color="#fff" />}
          </button>
          <button style={{ width: 50, height: 50, borderRadius: 999, background: T.white, border: `1px solid ${T.line}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="keyboard" size={22} color={T.body} /></button>
        </div>
        <span style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted }}>{listening ? 'Tap to stop · Switch to Chat or Translate' : 'Tap mic to start speaking'}</span>
      </div>
    </div>
  );
}

function TranslateMode({ lang }) {
  const langName = { EN: 'English', FR: 'French', ZH: 'Chinese', KR: 'Korean', JP: 'Japanese', KH: 'Khmer' };
  const samples = { EN: 'How much is a tuk-tuk to Angkor Wat?', FR: 'Combien coûte un tuk-tuk pour Angkor Wat ?', ZH: '去吴哥窟的嘟嘟车多少钱？', KR: '앙코르 와트까지 툭툭 요금이 얼마예요?', JP: 'アンコールワットまでトゥクトゥクはいくらですか？', KH: 'តម្លៃតុកតុកទៅអង្គរវត្តប៉ុន្មាន?' };
  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px', background: T.cream }}>
      <Panel label={`You speak · ${langName[lang] || 'English'}`} flag={(HM.LANGS.find(l => l.code === lang) || {}).flag} text={samples[lang] || samples.EN} accent={T.navy} />
      <div style={{ display: 'flex', justifyContent: 'center', margin: '14px 0' }}>
        <div style={{ width: 44, height: 44, borderRadius: 999, background: T.gold, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 6px 16px rgba(207,154,53,0.4)' }}><Icon name="translate" size={22} color="#fff" /></div>
      </div>
      <Panel label="Local hears · Khmer" flag="🇰🇭" text="តម្លៃតុកតុកទៅអង្គរវត្តប៉ុន្មាន?" sub="Tâmlai tuk-tuk tɨw Ângkôr Voat ponmaan?" accent={T.teal} />
      <div style={{ display: 'flex', gap: 11, marginTop: 18 }}>
        <button style={{ flex: 1, padding: 15, borderRadius: 14, background: T.navy, border: 'none', color: '#fff', cursor: 'pointer', fontFamily: SANS, fontWeight: 700, fontSize: 15, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9 }}><Icon name="mic" size={19} color="#fff" />Hold to speak</button>
        <button style={{ width: 56, borderRadius: 14, background: T.white, border: `1px solid ${T.line}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="volume" size={22} color={T.navy} /></button>
      </div>
    </div>
  );
}
function Panel({ label, flag, text, sub, accent }) {
  return (
    <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 18, padding: 18, borderLeft: `4px solid ${accent}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <span style={{ fontSize: 18 }}>{flag}</span>
        <span style={{ fontFamily: SANS, fontWeight: 700, fontSize: 13, color: T.muted, letterSpacing: 0.3 }}>{label}</span>
      </div>
      <div style={{ fontFamily: SANS, fontSize: 19, color: T.ink, lineHeight: 1.4, fontWeight: 600 }}>{text}</div>
      {sub && <div style={{ fontFamily: SANS, fontSize: 13.5, color: T.muted, marginTop: 6, fontStyle: 'italic' }}>{sub}</div>}
    </div>
  );
}

function AIGuide({ onBack, lang, onAction }) {
  const [mode, setMode] = React.useState('chat');
  const status = mode === 'voice' ? 'Listening…' : mode === 'translate' ? 'Translate · live' : 'Online · Multilingual';
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.cream }}>
      <GuideHeader onBack={onBack} status={status} mode={mode} setMode={setMode} />
      {mode === 'chat' && <ChatMode onAction={onAction} />}
      {mode === 'voice' && <VoiceMode />}
      {mode === 'translate' && <TranslateMode lang={lang} />}
    </div>
  );
}

Object.assign(window, { AIGuide });
