// Teach-me tab — chat-like interface that streams Seamenese translations from Claude.
const { useState: useStateT, useRef: useRefT, useEffect: useEffectT } = React;

const SAMPLE_QUESTIONS = [
  "How do I say 'I love your friend'?",
  "How do I say 'I'm dreading Monday'?",
  "How do I say 'stop sending me long voice memos'?",
  "How do I say 'we left without saying goodbye'?",
  "How do I say 'that joke was bad and you know it'?",
];

function TeachMeView({ data }) {
  const [history, setHistory] = useStateT([]);
  const [input, setInput] = useStateT('');
  const [streaming, setStreaming] = useStateT(false);
  const [streamSections, setStreamSections] = useStateT([]);
  const [error, setError] = useStateT('');
  const scrollRef = useRefT();

  useEffectT(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [history, streamSections]);

  async function ask(q) {
    if (!q.trim() || streaming) return;
    const question = q.trim();
    setInput('');
    setStreaming(true);
    setStreamSections([]);
    setError('');

    try {
      const res = await fetch('/api/explain', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
        throw new Error(err.error || `Request failed: ${res.status}`);
      }

      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let cur = [];

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        const lines = buffer.split('\n');
        buffer = lines.pop();

        let eventType = null;
        for (const line of lines) {
          if (line.startsWith('event: ')) {
            eventType = line.slice(7).trim();
          } else if (line.startsWith('data: ') && eventType) {
            try {
              const payload = JSON.parse(line.slice(6));
              if (eventType === 'section-start') {
                cur = [...cur, { kind: payload.kind, text: '' }];
                setStreamSections([...cur]);
              } else if (eventType === 'token' && cur.length > 0) {
                const last = cur[cur.length - 1];
                cur = [...cur.slice(0, -1), { ...last, text: last.text + payload.text }];
                setStreamSections([...cur]);
              } else if (eventType === 'error') {
                throw new Error(payload.error || 'Stream error');
              }
            } catch (parseErr) {
              if (parseErr.message !== 'Stream error') {
                // JSON parse error — ignore partial data
              } else {
                throw parseErr;
              }
            }
            eventType = null;
          } else if (line === '') {
            eventType = null;
          }
        }
      }

      if (cur.length > 0) {
        setHistory(h => [...h, { question, sections: cur }]);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setStreamSections([]);
      setStreaming(false);
    }
  }

  function handleSubmit(e) {
    e.preventDefault();
    ask(input);
  }

  return (
    <div className="teach-shell">
      <aside className="teach-side">
        <div className="eyebrow"><span className="rule"></span>How this works</div>
        <h3 className="serif teach-side-title">Type a sentence. Get the linguistics.</h3>
        <p className="teach-side-lede">
          Claude reads the dictionary, picks words, applies grammar rules, conjugates,
          and tells you what it had to invent on the spot.
        </p>

        <div className="eyebrow" style={{ marginTop: 24 }}><span className="rule"></span>Try one</div>
        <ul className="teach-samples">
          {SAMPLE_QUESTIONS.map((q, i) => (
            <li key={i}>
              <button className="teach-sample" onClick={() => ask(q)} disabled={streaming}>
                <span className="teach-sample-num mono">{String(i + 1).padStart(2, '0')}</span>
                <span className="teach-sample-text serif" style={{ fontStyle: 'italic' }}>{q}</span>
              </button>
            </li>
          ))}
        </ul>

        <div className="teach-side-foot">
          <span className="hand" style={{ fontSize: 18, color: 'var(--accent-warm)' }}>
            warning: the bot will guess.<br/>verify with jorn before tattooing.
          </span>
        </div>
      </aside>

      <main className="teach-main">
        <div className="teach-stream" ref={scrollRef}>
          {history.length === 0 && streamSections.length === 0 && !error ? (
            <div className="teach-empty">
              <div className="teach-empty-glyph serif">¿</div>
              <h2 className="serif teach-empty-title">What do you want to say?</h2>
              <p className="teach-empty-lede">
                Ask in plain English. You'll get a Seamenese translation with annotated grammar,
                conjugation, and a note for anything we had to make up.
              </p>
            </div>
          ) : null}

          {history.map((h, i) => (
            <Exchange key={i} question={h.question} sections={h.sections} />
          ))}

          {streamSections.length > 0 && (
            <Exchange question={'…'} sections={streamSections} streaming />
          )}

          {error && (
            <div style={{ padding: '20px 0' }}>
              <div className="ai-result" style={{ borderColor: 'var(--accent-warm)', background: 'rgba(244, 63, 94, 0.08)' }}>
                <span style={{ color: 'var(--accent-warm)' }}>{error}</span>
              </div>
            </div>
          )}
        </div>

        <form className="teach-input-wrap" onSubmit={handleSubmit}>
          <span className="teach-input-prompt mono">›</span>
          <input
            className="teach-input"
            placeholder="How do I say…"
            value={input}
            onChange={e => setInput(e.target.value)}
            disabled={streaming}
            autoFocus
          />
          <button className="btn btn-warm" type="submit" disabled={streaming || !input.trim()}>
            {streaming ? 'thinking…' : 'translate ↵'}
          </button>
        </form>
      </main>
    </div>
  );
}

function Exchange({ question, sections, streaming }) {
  return (
    <div className="exchange">
      <div className="exchange-q">
        <span className="exchange-q-label mono">YOU</span>
        <p className="serif" style={{ fontStyle: 'italic', fontSize: 18, color: 'var(--paper)' }}>{question}</p>
      </div>
      <div className="exchange-a">
        <span className="exchange-a-label mono">BONK BOT</span>
        <div className="exchange-a-body">
          {sections.map((s, i) => (
            <SectionBlock key={i} kind={s.kind} text={s.text} streaming={streaming && i === sections.length - 1} />
          ))}
        </div>
      </div>
    </div>
  );
}

const SECTION_LABEL = {
  intro: '01 · Parsing',
  'word-choice': '02 · Word choices',
  grammar: '03 · Grammar',
  conjugation: '04 · Conjugation',
  answer: '05 · Answer',
  flags: '06 · Caveats',
};

function SectionBlock({ kind, text, streaming }) {
  return (
    <div className={`teach-section kind-${kind}`}>
      <div className="teach-section-label mono">{SECTION_LABEL[kind] || kind}</div>
      <div className="teach-section-text">
        {renderInline(text)}
        {streaming && <span className="teach-cursor" />}
      </div>
    </div>
  );
}

function renderInline(text) {
  const parts = [];
  let buf = '';
  let i = 0;
  let key = 0;
  const flush = () => {
    if (buf) {
      const segs = buf.split('\n');
      segs.forEach((seg, idx) => {
        if (seg) parts.push(<span key={key++}>{seg}</span>);
        if (idx < segs.length - 1) parts.push(<br key={key++} />);
      });
      buf = '';
    }
  };
  while (i < text.length) {
    if (text[i] === '*' && text[i + 1] === '*') {
      flush();
      const end = text.indexOf('**', i + 2);
      if (end === -1) { buf += text.slice(i); break; }
      parts.push(<strong key={key++} className="serif" style={{ color: 'var(--paper)', fontStyle: 'italic', fontWeight: 500 }}>{text.slice(i + 2, end)}</strong>);
      i = end + 2;
    } else {
      buf += text[i++];
    }
  }
  flush();
  return parts;
}

Object.assign(window, { TeachMeView });
