/* HTD Growth — Live AI Coach chat (real Claude via window.claude.complete) */
(function () {
  const { useState, useRef, useEffect } = React;
  const Icon = window.HTDIcon;
  const F = window.HTD_FIX;

  const SYSTEM = `You are the HTD Resilience Architect — the in-app coach for "Hard Things Daily", a tactical discipline app.
Voice: direct, short, purposeful, specific. Like a calm special-forces coach. No emoji. No "crush it" or "beast mode". Never give medical advice; for pain or red flags say to stop and recover.
Athlete context: readiness 85/100 (good), HRV 62 (+5), streak 18 days, today's mission RUN 10K FASTED (difficulty 8/10, Zone 2), weakest axis mental toughness (54), avoidance pattern: skips pre-7AM efforts after <6h sleep, crew IRONCROWN 9/12 done today.
Answer in at most 3 short sentences or up to 4 short bullet lines (use "·" as the bullet). PLAIN TEXT ONLY — never use markdown, asterisks, or headers. Be concrete: paces, times, ritual steps.`;

  function CoachChat() {
    const [msgs, setMsgs] = useState([
      { role: 'coach', text: 'Architect online. Readiness 85, streak 18, mission is a fasted 10K in Zone 2. What do you need?' },
    ]);
    const [draft, setDraft] = useState('');
    const [busy, setBusy] = useState(false);
    const scrollRef = useRef(null);

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

    const send = async (text) => {
      const q = (text || draft).trim();
      if (!q || busy) return;
      setDraft('');
      setMsgs(m => [...m, { role: 'you', text: q }]);
      setBusy(true);
      try {
        const history = msgs.slice(-6).map(m => (m.role === 'you' ? 'Athlete: ' : 'Coach: ') + m.text).join('\n');
        const reply = await window.claude.complete(
          SYSTEM + '\n\nConversation so far:\n' + history + '\nAthlete: ' + q + '\nCoach:');
        setMsgs(m => [...m, { role: 'coach', text: (reply || '').trim() || 'Signal lost. Ask again.' }]);
      } catch (e) {
        setMsgs(m => [...m, { role: 'coach', text: 'Link to AI memory dropped — that happens offline or when rate-limited. Ask again in a moment.' }]);
      }
      setBusy(false);
    };

    const chips = ['Brief me for today', 'I only slept 5 hours', 'My knee feels off', 'Make tomorrow harder'];

    return (
      <div className="screen-enter" style={{ display:'flex', flexDirection:'column', height:'100%', minHeight:430 }}>
        <div className="row between" style={{ padding:'12px 2px 10px' }}>
          <span className="label-mono acid" style={{ display:'flex', alignItems:'center', gap:6 }}>
            <span style={{ width:7, height:7, borderRadius:'50%', background:'var(--acid)', boxShadow:'0 0 7px var(--acid)' }} />
            LIVE · CLAUDE-POWERED</span>
          <span className="label-mono">GUIDANCE · NOT MEDICAL ADVICE</span>
        </div>
        <div ref={scrollRef} style={{ flex:1, overflowY:'auto', display:'flex', flexDirection:'column', gap:10, paddingBottom:12 }}>
          {msgs.map((m, i) => (
            <div key={i} style={{ alignSelf: m.role==='you' ? 'flex-end' : 'flex-start', maxWidth:'86%' }}>
              {m.role==='coach' && <div className="label-mono" style={{ marginBottom:4 }}>ARCHITECT</div>}
              <div style={{
                padding:'11px 13px', borderRadius:9, fontSize:13.5, lineHeight:1.5, whiteSpace:'pre-wrap',
                background: m.role==='you' ? 'rgba(152,255,16,0.1)' : 'var(--panel)',
                border: '1px solid ' + (m.role==='you' ? 'var(--border-active)' : 'var(--hairline)'),
                color: 'var(--bone)',
              }}>{m.text}</div>
            </div>
          ))}
          {busy && (
            <div style={{ alignSelf:'flex-start' }}>
              <div className="label-mono" style={{ marginBottom:4 }}>ARCHITECT</div>
              <div className="panel" style={{ padding:'11px 14px' }}>
                <span className="label-mono acid">ANALYZING ···</span>
              </div>
            </div>
          )}
        </div>
        <div className="row" style={{ flexWrap:'wrap', gap:7, paddingBottom:10 }}>
          {chips.map(c => (
            <button key={c} onClick={()=>send(c)} disabled={busy} className="label-mono" style={{
              padding:'8px 11px', borderRadius:6, cursor:'pointer', background:'var(--panel)',
              border:'1px solid var(--hairline-2)', color:'var(--bone-muted)', textTransform:'none', letterSpacing:.5 }}>{c}</button>
          ))}
        </div>
        <div className="row" style={{ gap:9 }}>
          <input value={draft} onChange={e=>setDraft(e.target.value)} onKeyDown={e=>e.key==='Enter'&&send()}
            placeholder="Ask the Architect…" disabled={busy}
            style={{ flex:1, height:46, background:'var(--panel)', border:'1px solid var(--hairline-2)', borderRadius:'var(--r)',
              color:'var(--bone)', fontFamily:'var(--ui)', fontSize:14, padding:'0 14px', outline:'none' }}
            onFocus={e=>e.target.style.borderColor='var(--border-active)'}
            onBlur={e=>e.target.style.borderColor='var(--hairline-2)'} />
          <button className="btn-primary" style={{ width:'auto', padding:'0 18px', fontSize:14, opacity: busy?0.5:1 }} onClick={()=>send()} disabled={busy}>SEND</button>
        </div>
      </div>
    );
  }

  window.HTDCoachChat = { CoachChat };
})();
