// screens-ai.jsx — AI Tutor (chat with OpenRouter) and helpers.

function TutorScreen({ theme, mascotOn, onTab }) {
  const [messages, setMessages] = React.useState(() => [
    { role: 'assistant', content: '你好！我是 Chopstick 🥢\nnǐ hǎo! wǒ shì Chopstick\nHi! I’m Chopstick — ask me anything in English or Chinese. I’ll reply with characters, pinyin, and English.' },
  ]);
  const [input, setInput] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [streaming, setStreaming] = React.useState('');
  const scrollRef = React.useRef(null);
  const abortRef = React.useRef(null);

  const hasKey = orHasKey();

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, streaming]);

  const send = async () => {
    const text = input.trim();
    if (!text || sending) return;
    if (!hasKey) { setError('Set your OpenRouter API key in Settings first.'); return; }
    setError(null);

    const next = [...messages, { role: 'user', content: text }];
    setMessages(next);
    setInput('');
    setSending(true);
    setStreaming('');

    const controller = new AbortController();
    abortRef.current = controller;

    try {
      const orMessages = [
        { role: 'system', content: TUTOR_SYSTEM },
        ...next.map((m) => ({ role: m.role, content: m.content })),
      ];
      const full = await orChatStream({
        messages: orMessages,
        temperature: 0.6, max_tokens: 700,
        signal: controller.signal,
        onToken: (_d, full) => setStreaming(full),
      });
      setMessages([...next, { role: 'assistant', content: full }]);
      setStreaming('');
    } catch (e) {
      if (e.name !== 'AbortError') setError(e.message);
      setStreaming('');
    } finally {
      setSending(false);
      abortRef.current = null;
    }
  };

  const stop = () => abortRef.current?.abort();

  const quickPrompts = [
    'How do I order coffee?',
    'Teach me 5 useful verbs.',
    'Make a short dialogue at a restaurant.',
    'Quiz me on family words.',
  ];

  return (
    <Screen theme={theme} scroll={false}>
      <div style={{ padding: '54px 16px 12px', borderBottom: `2px solid ${theme.fg}`, background: theme.surface }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {mascotOn && <Mascot theme={theme} mood="happy" size={56}/>}
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: theme.fontBody, fontSize: 11, letterSpacing: '0.15em', color: theme.fgMute, textTransform: 'uppercase' }}>
              AI TUTOR
            </div>
            <H theme={theme} size={26}>ASK ME ANYTHING</H>
          </div>
        </div>
      </div>

      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '14px 16px 8px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {messages.map((m, i) => <Bubble key={i} theme={theme} role={m.role} content={m.content}/>)}
        {streaming && <Bubble theme={theme} role="assistant" content={streaming} streaming/>}
        {error && (
          <div style={{
            background: theme.red, color: '#fff', padding: 10, borderRadius: theme.radius,
            border: `2px solid ${theme.fg}`, fontFamily: theme.fontBody, fontSize: 12,
          }}>
            ⚠ {error}
          </div>
        )}
        {!hasKey && messages.length === 1 && (
          <div style={{
            background: theme.yellow, color: theme.fg,
            border: `2px solid ${theme.fg}`, borderRadius: theme.radius,
            padding: 12, fontFamily: theme.fontBody, fontSize: 12, lineHeight: 1.4,
            boxShadow: `0 3px 0 0 ${theme.fg}`,
          }}>
            <div style={{ fontFamily: theme.fontHead, fontSize: 13, fontWeight: 700, marginBottom: 4 }}>NO API KEY YET</div>
            Add an OpenRouter key in Settings to unlock the AI tutor. The key stays on your device.
          </div>
        )}
        {messages.length <= 2 && (
          <div style={{ marginTop: 8 }}>
            <div style={{ fontFamily: theme.fontHead, fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: theme.fgMute, marginBottom: 6 }}>
              TRY ASKING
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {quickPrompts.map((q) => (
                <button key={q} onClick={() => setInput(q)} style={{
                  all: 'unset', cursor: 'pointer',
                  background: theme.surface, color: theme.fg,
                  border: `2px solid ${theme.fg}`, borderRadius: 999,
                  padding: '8px 12px', fontFamily: theme.fontBody, fontSize: 12,
                }}>{q}</button>
              ))}
            </div>
          </div>
        )}
      </div>

      <div style={{ padding: '8px 12px', borderTop: `2px solid ${theme.fg}`, background: theme.surface }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}>
          <textarea
            rows={1}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder={hasKey ? 'Ask in English or Chinese…' : 'Add an OpenRouter key in Settings'}
            disabled={!hasKey || sending}
            style={{
              flex: 1, resize: 'none',
              fontFamily: theme.fontBody, fontSize: 14,
              padding: '12px 14px',
              background: theme.bg, color: theme.fg,
              border: `2px solid ${theme.fg}`, borderRadius: theme.radius,
              outline: 'none', minHeight: 44, maxHeight: 120,
              opacity: hasKey ? 1 : 0.6,
            }}
          />
          {sending ? (
            <RetroBtn theme={theme} variant="danger" size="lg" onClick={stop}>STOP</RetroBtn>
          ) : (
            <RetroBtn theme={theme} variant="primary" size="lg" onClick={send} disabled={!input.trim() || !hasKey}>SEND</RetroBtn>
          )}
        </div>
      </div>

      <TabBar theme={theme} tab="tutor" onTab={onTab}/>
    </Screen>
  );
}

function Bubble({ theme, role, content, streaming }) {
  const isUser = role === 'user';
  return (
    <div style={{
      alignSelf: isUser ? 'flex-end' : 'flex-start',
      maxWidth: '85%',
      background: isUser ? theme.primary : theme.surface,
      color: isUser && theme.mode === 'dark' ? '#fff' : theme.fg,
      border: `2px solid ${theme.fg}`,
      borderRadius: theme.radius,
      padding: '10px 12px',
      boxShadow: isUser ? `0 3px 0 0 ${theme.yellow}` : `0 3px 0 0 ${theme.cyan}`,
      fontFamily: theme.fontBody, fontSize: 13, lineHeight: 1.55,
      whiteSpace: 'pre-wrap', wordBreak: 'break-word',
    }}>
      {renderTutorContent(theme, content, isUser)}
      {streaming && <span style={{
        display: 'inline-block', width: 8, height: 14, marginLeft: 2,
        background: theme.fg, verticalAlign: '-2px',
        animation: 'speakPulse 0.9s infinite',
      }}/>}
    </div>
  );
}

// Render a tutor reply by line: Chinese lines get the CN font + a speaker button.
// We treat lines with ANY CJK character as Chinese, lines with only pinyin tone
// chars or letters/spaces as pinyin (subtle accent color), everything else as
// English/body.
function renderTutorContent(theme, content, isUser) {
  if (isUser) return content;
  const lines = content.split('\n');
  return lines.map((line, i) => {
    const trimmed = line.trim();
    if (!trimmed) return <div key={i} style={{ height: 4 }}/>;
    const hasCJK = /[一-鿿]/.test(trimmed);
    const hasToneMark = /[āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜü]/.test(trimmed);

    if (hasCJK) {
      return (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '4px 0' }}>
          <button onClick={() => { primeSpeech(); speakZh(trimmed); }} style={{
            all: 'unset', cursor: 'pointer', width: 26, height: 26, flexShrink: 0,
            border: `1.5px solid ${theme.fg}`, borderRadius: '50%',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: theme.yellow,
          }}>
            <Speaker theme={theme} size={14} color={theme.fg}/>
          </button>
          <span style={{ fontFamily: theme.fontCN, fontSize: 18, fontWeight: 700 }}>{trimmed}</span>
        </div>
      );
    }
    if (hasToneMark || /^[a-zA-Z0-9\s.,'?!:\-—]+$/.test(trimmed) && /[a-z]/i.test(trimmed) && trimmed.length < 60) {
      // Heuristic: short alpha line is likely pinyin in tutor format.
      return (
        <div key={i} style={{ fontFamily: theme.fontPinyin, fontSize: 13, color: theme.primary, margin: '2px 0' }}>
          {trimmed}
        </div>
      );
    }
    return <div key={i} style={{ margin: '2px 0' }}>{trimmed}</div>;
  });
}

Object.assign(window, { TutorScreen });
