// AskBox — inline Q&A.
//
// On GitHub Pages there is no window.claude helper (that only exists inside
// Claude's artifact viewer), so questions go to the video-guide-ask Cloudflare
// Worker in ../worker. It holds the Anthropic key and the tutor instructions;
// the page only sends the question and the section context.
const ASK_URL = 'https://video-guide-ask.akesha.workers.dev';

const { useState, useRef, useCallback } = React;

function AskBox({ context, title = 'Ask the assistant a question', subtitle = 'Stuck? Type in plain English — the assistant has read this whole guide.', suggestions = [], compact = false }) {
  const [q, setQ] = useState('');
  const [asked, setAsked] = useState('');
  const [answer, setAnswer] = useState('');
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState('');
  const taRef = useRef(null);

  const submit = useCallback(async (questionText) => {
    const text = (questionText ?? q).trim();
    if (!text || loading) return;
    setAsked(text);
    setQ('');
    setLoading(true);
    setAnswer('');
    setErr('');
    try {
      const res = await fetch(ASK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: text, context }),
      });
      const data = await res.json().catch(() => null);
      // 429 and refusal messages from the Worker are written for readers; show them as-is.
      if (res.status === 429 || res.status === 422) throw Object.assign(new Error(data?.error), { friendly: true });
      if (!res.ok || !data?.answer) throw new Error(`Assistant ${res.status}: ${data?.error || 'no answer'}`);
      setAnswer(data.answer);
    } catch (e) {
      console.error(e);
      setErr(e.friendly && e.message ? e.message : 'Sorry — something went wrong reaching the assistant. Try again in a moment.');
    } finally {
      setLoading(false);
    }
  }, [q, loading, context]);

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      submit();
    }
  };

  const clearAll = () => { setAsked(''); setAnswer(''); setErr(''); };

  return (
    <div className="ask-box">
      <div className="ask-head">
        <div className="ask-icon"><Icon d={Icons.question} size={18}/></div>
        <div className="ask-title">{title}<small>{subtitle}</small></div>
      </div>
      <div className="ask-form">
        <textarea ref={taRef} className="ask-input" value={q}
                  onChange={(e) => setQ(e.target.value)} onKeyDown={onKey}
                  placeholder={compact ? 'What\u2019s unclear about this step?' : 'e.g. What does "drift" mean?'}
                  rows={1}/>
        <button className="ask-submit" onClick={() => submit()} disabled={loading || !q.trim()}>
          {loading ? 'Asking…' : <>Ask <Icon d={Icons.send} size={12}/></>}
        </button>
      </div>
      {suggestions.length > 0 && !asked && !loading && (
        <div className="ask-suggestions">
          {suggestions.map((s, i) => (
            <button key={i} className="suggest-chip" onClick={() => submit(s)}>{s}</button>
          ))}
        </div>
      )}
      {(asked || loading || err) && (
        <div className="ask-answer">
          {asked && (<>
            <div className="ask-q">Your question</div>
            <div className="ask-q-text">{asked}</div>
          </>)}
          {loading && <div className="ask-loading"><span className="spinner"></span>Thinking it through…</div>}
          {err && <div className="ask-a-body"><p style={{ color: 'var(--coral)' }}>{err}</p></div>}
          {answer && !loading && (
            <div className="ask-a-body">
              {answer.split(/\n\n+/).map((p, i) => <p key={i}>{p}</p>)}
            </div>
          )}
          {(answer || err) && !loading && (
            <button className="ask-clear" onClick={clearAll}>↺ Ask another</button>
          )}
        </div>
      )}
    </div>
  );
}

window.AskBox = AskBox;
