/* AI Tutor — a real working homework helper powered by claude.complete.
   Kid-friendly: explains and guides rather than just handing over answers. */
const JL_TUTOR_PRIMER = [
  { role:'user', content:
    "You are JewelLink's friendly AI homework tutor for EJ, a 6th-grade student (about 11 years old). " +
    "Rules: Be warm, encouraging and patient. Explain concepts simply with everyday examples. " +
    "Guide the student toward the answer with hints and small steps instead of just giving the final answer outright; " +
    "for factual questions you may answer directly but still explain why. Keep replies short — 2 to 4 short sentences or a few bullet points. " +
    "Use plain language a middle-schooler understands. Write in plain text only — do not use markdown, asterisks, or bold formatting. " +
    "If asked something inappropriate or unrelated to schoolwork, gently steer back to learning. " +
    "Acknowledge you understand and then wait for the first question." },
  { role:'assistant', content:"Got it! I'm EJ's homework buddy. I'll keep things friendly and simple, and help EJ figure things out step by step. What are we working on today?" },
];
const JL_TUTOR_SUGGESTIONS = [
  "Explain fractions simply",
  "Help me start my book report",
  "Why is the sky blue?",
  "Quiz me on multiplication",
];

function TutorScreen({ onBack }) {
  const [msgs, setMsgs] = React.useState([
    { role:'assistant', content:"Hi EJ! I'm your AI tutor. Ask me anything about your homework — math, science, reading, you name it. I'll help you understand it, not just give answers." },
  ]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [msgs, busy]);

  const send = async (text) => {
    const q = (text != null ? text : input).trim();
    if (!q || busy) return;
    setInput('');
    const next = [...msgs, { role:'user', content:q }];
    setMsgs(next);
    setBusy(true);
    try {
      if (!(window.claude && window.claude.complete)) throw new Error('offline');
      const convo = JL_TUTOR_PRIMER.concat(next.map(m => ({ role:m.role, content:m.content })));
      const reply = await window.claude.complete({ messages: convo });
      setMsgs(m => [...m, { role:'assistant', content: (reply || '').trim() || "Hmm, I didn't catch that — can you ask again?" }]);
    } catch (e) {
      setMsgs(m => [...m, { role:'assistant', content:"I can't reach my tutor service right now — check your connection and try again in a moment.", err:true }]);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:'var(--gray-50)' }}>
      <PushBar title="AI Tutor" onBack={onBack} bell={false} />

      {/* messages */}
      <div ref={scrollRef} style={{ flex:1, overflow:'auto', padding:'16px 16px 8px' }}>
        {/* AI identity chip */}
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', marginBottom:16 }}>
          <div style={{ width:54, height:54, borderRadius:16, background:'var(--grad-ai)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'var(--shadow-md)' }}>
            <Icon name="bot" size={28} color="#fff" />
          </div>
          <div style={{ fontSize:13, fontWeight:700, color:'var(--gray-500)', marginTop:8 }}>JewelLink AI Tutor</div>
        </div>

        {msgs.map((m,i) => (
          <div key={i} style={{ display:'flex', justifyContent: m.role==='user'?'flex-end':'flex-start', marginBottom:10 }}>
            <div style={{
              maxWidth:'80%', padding:'11px 14px', borderRadius:16, fontSize:14, lineHeight:1.5,
              fontFamily:'var(--font-sans)', whiteSpace:'pre-wrap',
              background: m.role==='user' ? 'var(--navy-600)' : (m.err?'var(--danger-100)':'#fff'),
              color: m.role==='user' ? '#fff' : (m.err?'var(--danger-600)':'var(--ink)'),
              border: m.role==='user' ? '0' : '1px solid var(--gray-200)',
              borderBottomRightRadius: m.role==='user'?4:16,
              borderBottomLeftRadius: m.role==='user'?16:4,
              boxShadow: m.role==='user'?'none':'var(--shadow-sm)',
            }}>{m.content}</div>
          </div>
        ))}

        {busy && (
          <div style={{ display:'flex', justifyContent:'flex-start', marginBottom:10 }}>
            <div style={{ padding:'13px 16px', borderRadius:16, borderBottomLeftRadius:4, background:'#fff', border:'1px solid var(--gray-200)', boxShadow:'var(--shadow-sm)', display:'flex', gap:5 }}>
              <span className="jl-typing-dot" style={{ animationDelay:'0s' }} />
              <span className="jl-typing-dot" style={{ animationDelay:'.18s' }} />
              <span className="jl-typing-dot" style={{ animationDelay:'.36s' }} />
            </div>
          </div>
        )}

        {/* suggestions (only before first question) */}
        {msgs.length === 1 && !busy && (
          <div style={{ display:'flex', flexWrap:'wrap', gap:8, marginTop:8, justifyContent:'center' }}>
            {JL_TUTOR_SUGGESTIONS.map(s => (
              <button key={s} onClick={()=>send(s)} style={{ background:'#fff', border:'1px solid var(--gray-200)', borderRadius:'999px', padding:'9px 14px', fontSize:12.5, fontWeight:600, color:'var(--blue-600)', cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-xs)' }}>{s}</button>
            ))}
          </div>
        )}
      </div>

      {/* input bar */}
      <div style={{ padding:'10px 14px 30px', background:'#fff', borderTop:'1px solid var(--gray-200)', display:'flex', alignItems:'flex-end', gap:9 }}>
        <textarea
          value={input}
          onChange={e=>setInput(e.target.value)}
          onKeyDown={e=>{ if(e.key==='Enter' && !e.shiftKey){ e.preventDefault(); send(); } }}
          placeholder="Ask your tutor anything…"
          rows={1}
          style={{ flex:1, resize:'none', maxHeight:90, border:'1.5px solid var(--gray-200)', borderRadius:18, padding:'11px 14px', fontSize:14, fontFamily:'var(--font-sans)', outline:'none', background:'var(--gray-50)', color:'var(--ink)', lineHeight:1.4 }}
        />
        <button onClick={()=>send()} disabled={!input.trim()||busy} style={{ width:44, height:44, borderRadius:'999px', border:0, flex:'0 0 auto', display:'flex', alignItems:'center', justifyContent:'center', cursor: (input.trim()&&!busy)?'pointer':'default', background:(input.trim()&&!busy)?'var(--navy-600)':'var(--gray-200)' }}>
          <Icon name="arrow-up" size={20} color={(input.trim()&&!busy)?'#fff':'var(--gray-500)'} stroke={2.4} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { TutorScreen });
