// Healify V2 — Chat with Anna

function ChatScreen({ onNavigate, onBack, topic, isRoot }) {
  const [composer, setComposer] = React.useState('');
  const [showHistory, setShowHistory] = React.useState(false);
  const [showAttach, setShowAttach] = React.useState(false);
  const [annaTyping, setAnnaTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

  const seed = topic === 'bp' ? bpThread : topic === 'movement' ? movementThread : topic === 'evening' ? eveningThread : defaultThread;
  const [messages, setMessages] = React.useState(seed);

  // Reset when topic changes
  React.useEffect(() => {
    setMessages(seed);
  }, [topic]);

  React.useEffect(() => {
    if (!scrollRef.current) return;
    requestAnimationFrame(() => {
      if (scrollRef.current) scrollRef.current.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
    });
  }, [messages, annaTyping]);

  const annaReply = async (userText) => {
    // Try real backend first — `POST /api/chat/graph` via AgentCore.
    if (typeof window !== 'undefined' && window.healifyApi && window.healifyApi.getToken()) {
      try {
        const res = await window.healifyApi.chat.graph({
          message: userText,
          topic,
          focus: topic === 'bp' ? 'bloodwork' : undefined,
        });
        const text = res?.content || res?.message || res?.text || res?.reply || res?.response;
        if (text) {
          return {
            content: <div>{typeof text === 'string' ? text : JSON.stringify(text)}</div>,
            quickReplies: res.quickReplies || res.suggestions || res.followups || undefined,
          };
        }
      } catch (e) { /* fall through to canned replies */ }
    }
    // Fallback (no token / network error / browser preview).
    const t = userText.toLowerCase();
    if (t.includes('bp') || t.includes('blood pressure') || t.includes('pressure')) {
      return { content: <div>Your last 5 reads average <strong style={{ fontWeight: 600 }}>128/82</strong>. That's Stage 1. Want me to schedule a 5-day low-sodium plan + 20-min daily walks and we re-test Friday?</div>, quickReplies: ['Yes, plan it', 'Just the walks', 'Show me the data'] };
    }
    if (t.includes('meal') || t.includes('food') || t.includes('plan')) {
      return { content: <div>I'll build a 3-day plan tuned to your slow-caffeine metabolism and low ferritin. Want <strong style={{ fontWeight: 600 }}>120g protein</strong> and under <strong style={{ fontWeight: 600 }}>1,500mg sodium</strong>?</div>, quickReplies: ['Sounds good', 'More protein', 'Vegetarian please'] };
    }
    if (t.includes('sleep') || t.includes('tired')) {
      return { content: <div>Looking at last night: you went down at 11:18pm, woke 2× before 4am. Likely the late wine — alcohol cuts your deep sleep ~22%. Try cutting it Tue–Thu for two weeks?</div>, quickReplies: ['Try it', 'What else?', 'Set a reminder'] };
    }
    if (t.includes('steps') || t.includes('walk') || t.includes('exercise')) {
      return { content: <div>You're at <strong style={{ fontWeight: 600 }}>8,420 steps</strong> today. Two short walks would bring you over 10k. I can block 8pm on your calendar.</div>, quickReplies: ['Block it', 'Move to 7pm', "I'll do it"] };
    }
    return { content: <div>Got it — let me pull the relevant data and think through this. Anything specific you want me to weigh more (sleep, BP, mood)?</div>, quickReplies: ['Sleep', 'Heart', 'Mood', 'Just talk'] };
  };

  const send = (text) => {
    const value = (text ?? composer).trim();
    if (!value) return;
    const now = new Date();
    const time = `${now.getHours()}:${String(now.getMinutes()).padStart(2, '0')}`;
    setMessages((m) => [...m, { from: 'user', time, content: value }]);
    setComposer('');
    setAnnaTyping(true);
    (async () => {
      const reply = await annaReply(value);
      const replyTime = `${new Date().getHours()}:${String(new Date().getMinutes()).padStart(2, '0')}`;
      setMessages((m) => [...m, { from: 'anna', time: replyTime, content: reply.content, quickReplies: reply.quickReplies }]);
      setAnnaTyping(false);
    })();
  };

  return (
    <div data-screen-label="03 Chat" style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: 'var(--t-bg)' }}>
      {/* Header — extends behind status bar */}
      <div style={{ padding: '60px 12px 8px', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--t-surface)', borderBottom: '1px solid var(--t-border)' }}>
        {!isRoot && onBack ? <HBackButton onClick={onBack} /> : <div style={{ width: 8 }} />}
        <HAnnaAvatar size={36} state={annaTyping ? 'thinking' : 'idle'} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.2px' }}>Anna</div>
          <div style={{ fontSize: 11, color: 'var(--success)', display: 'flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--success)' }} />
            {annaTyping ? 'Typing…' : 'Reading your data · Online'}
          </div>
        </div>
        <HIconButton icon="clock" tone="soft" size={36} onClick={() => setShowHistory(true)} />
        <HIconButton icon="voice" tone="orange" size={36} onClick={() => onNavigate('voice')} />
      </div>

      {/* History drawer */}
      {showHistory &&
      <div onClick={() => setShowHistory(false)} style={{ position: 'absolute', inset: 0, zIndex: 30, background: 'rgba(0,0,0,0.4)', display: 'flex', justifyContent: 'flex-end' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: 280, background: 'var(--t-surface)', height: '100%', boxShadow: 'var(--shadow-lg)', padding: '16px 14px', overflowY: 'auto' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <div className="h-display" style={{ fontSize: 18, fontWeight: 600 }}>Threads</div>
              <button onClick={() => setShowHistory(false)} style={{ width: 30, height: 30, borderRadius: 999, background: 'var(--t-ink-04)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Glyph name="close" size={14} />
              </button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[
            { t: 'Blood pressure — what now?', p: 'BP 130/85, sodium', d: 'Today', active: true },
            { t: 'Better sleep tonight', p: 'Wind-down protocol', d: 'Yesterday' },
            { t: 'Iron levels low — diet swaps', p: 'Try lentils, beef', d: '3d' },
            { t: 'Why is HRV dropping?', p: 'Recovery, alcohol', d: 'Apr 21' },
            { t: 'Headache pattern', p: 'Possible triggers', d: 'Apr 14' },
            { t: 'Why am I always tired at 3pm?', p: 'Blood sugar dips', d: 'Mar 28' }].
            map((tt, i) =>
            <button key={i} style={{ padding: '10px 12px', borderRadius: 12, background: tt.active ? 'var(--t-cream)' : 'transparent', textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 2, border: tt.active ? '1px solid rgba(255,105,66,0.18)' : 'none' }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--t-fg-1)', letterSpacing: '-0.2px' }}>{tt.t}</div>
                  <div style={{ fontSize: 11, color: 'var(--t-fg-3)' }}>{tt.p} · {tt.d}</div>
                </button>
            )}
            </div>
            <div style={{ marginTop: 16 }}>
              <HPrimaryButton variant="ink" full size="md" icon="plus">New thread</HPrimaryButton>
            </div>
          </div>
        </div>
      }

      {/* Thread title */}
      <div style={{ padding: '14px 16px 8px' }}>
        <div className="h-label">Thread</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 4, lineHeight: 1.2 }}>
          {topic === 'bp' ? 'Blood pressure — what now?' :
          topic === 'movement' ? 'Why are my steps low?' :
          topic === 'evening' ? 'Tonight\'s wind-down' :
          'Catch up'}
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} className="scroll-y" style={{ flex: 1, padding: '14px 16px 4px', overflowY: 'auto', WebkitMaskImage: 'linear-gradient(to bottom, transparent 0, #000 18px)', maskImage: 'linear-gradient(to bottom, transparent 0, #000 18px)' }}>
        {messages.map((m, i) =>
        <React.Fragment key={i}>
            <HChatBubble from={m.from} time={m.time} annaState={m.annaState} delay={i < seed.length ? i * 120 : 0}>{m.content}</HChatBubble>
            {m.quickReplies &&
          <div className="fade-up" style={{ margin: '-4px 0 14px 42px', animationDelay: `${(i < seed.length ? i * 120 : 0) + 250}ms` }}>
                <HQuickReplies items={m.quickReplies} onPick={(q) => send(q)} />
              </div>
          }
          </React.Fragment>
        )}
        {annaTyping && <HTyping />}
        <div style={{ height: 6 }} />
      </div>

      {/* Attach sheet — portal to body so it overlays the tab bar */}
      {showAttach && ReactDOM.createPortal(
        <div onClick={() => setShowAttach(false)} style={{ position: 'fixed', inset: 0, zIndex: 999, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ width: 'min(380px, 100%)', background: 'var(--t-surface)', borderTopLeftRadius: 28, borderTopRightRadius: 28, padding: '20px 18px 32px', color: 'var(--t-fg-1)', maxHeight: '70vh', overflowY: 'auto', animation: 'slide-up 280ms cubic-bezier(.2,.6,.2,1) both' }}>
            <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--t-ink-12)', margin: '0 auto 14px' }} />
            <div className="h-display" style={{ fontSize: 22, marginBottom: 14 }}>Attach</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {[
              { i: 'scan', t: 'Photo / scan', s: 'Bloodwork, plate, label' },
              { i: 'heart', t: 'Health data', s: 'A trend from Apple Health' },
              { i: 'mic', t: 'Voice memo', s: 'Hands-free thought' },
              { i: 'calendar', t: 'A day', s: 'Anything from that day' }].
              map((o) =>
              <button key={o.t} onClick={() => {setShowAttach(false);send(`Attached: ${o.t}`);}} style={{ padding: 14, borderRadius: 16, textAlign: 'left', background: 'var(--t-ink-04)', color: 'var(--t-fg-1)' }}>
                  <div style={{ width: 36, height: 36, borderRadius: 12, background: 'var(--t-cream)', color: 'var(--brand-orange-vibey)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>
                    <Glyph name={o.i} size={18} />
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.2px' }}>{o.t}</div>
                  <div style={{ fontSize: 11, color: 'var(--t-fg-3)', marginTop: 2 }}>{o.s}</div>
                </button>
              )}
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* Composer */}
      <div style={{ padding: '10px 12px 110px', background: 'var(--t-bg)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 8px 8px 14px', background: 'var(--t-surface)', borderRadius: 999, boxShadow: 'var(--shadow-md)' }}>
          <button onClick={() => setShowAttach(true)} aria-label="Attach" style={{ width: 32, height: 32, borderRadius: 999, background: 'var(--t-ink-04)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--t-fg-1)' }}>
            <Glyph name="plus" size={16} />
          </button>
          <input
            value={composer}
            onChange={(e) => setComposer(e.target.value)}
            onKeyDown={(e) => {if (e.key === 'Enter' && composer.trim()) send();}}
            placeholder="Type a message…"
            style={{ flex: 1, border: 'none', outline: 'none', fontSize: 15, background: 'transparent', color: 'var(--t-fg-1)', fontFamily: 'var(--font-body)' }} />
          
          {composer ?
          <button onClick={() => send()} aria-label="Send" style={{ width: 36, height: 36, borderRadius: 999, background: 'var(--grad-warm-orange)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-orange)' }}>
              <Glyph name="send" size={16} />
            </button> :

          <button onClick={() => onNavigate('voice')} aria-label="Voice" style={{ width: 36, height: 36, borderRadius: 999, background: 'var(--t-pill)', color: 'var(--t-pill-fg)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Glyph name="mic" size={16} />
            </button>
          }
        </div>
      </div>
    </div>);

}

// ============================================================================
// THREADS — the rich Anna content
// ============================================================================
const bpThread = [
{ from: 'user', time: '9:42', content: 'Hi Anna, my latest reading was 130/85. Should I be worried?' },
{
  from: 'anna', annaState: 'idle', time: '9:42',
  content:
  <div>
        <div>You're right to pay attention. <strong style={{ fontWeight: 600 }}>130/85 mmHg</strong> sits just inside Stage 1 hypertension. Not alarming, but worth steering back down.</div>
        <HBubbleDataCard
      title="BP this week"
      value="128/82"
      unit="avg · 5 reads"
      sub="Stage 1 · ≥130/80"
      chart={<HMiniBars data={[
      { value: 124, label: 'M' }, { value: 126, label: 'T' }, { value: 128, label: 'W' },
      { value: 131, label: 'T' }, { value: 128, label: 'F' }, { value: 132, label: 'S' }, { value: 130, label: 'S' }]
      } width={130} height={56} color="var(--brand-orange-vibey)" />} />
    
        <div style={{ marginTop: 12, fontSize: 14, color: 'var(--t-fg-2)' }}>Here are <strong style={{ fontWeight: 600, color: 'var(--t-fg-1)' }}>three things</strong> I'd try before your next reading:</div>
        <HNumberedActions items={[
    { title: 'Cut sodium to under 1,500 mg/day', body: 'Your nutrition log shows 2,800 mg avg. Lunch deli meat + chips alone are 1,600 mg.' },
    { title: 'Add a 20-minute brisk walk', body: 'Mid-afternoon is best — your BP dips ~5 mmHg after movement.' },
    { title: 'Hold off evening wine for 2 weeks', body: 'Even one drink raises systolic 3–7 mmHg in your data. We can re-test after.' }]
    } />
        <HSourceChips items={[
    { label: 'Last 5 BP reads' },
    { label: 'Nutrition · 14 days' },
    { label: 'Activity · Apple Health', color: 'var(--focus-fitness)' }]
    } />
      </div>,

  quickReplies: ['Build a low-sodium plan', 'Schedule the walk', 'What if it doesn\'t drop?', 'Show heart trends']
}];


const movementThread = [
{ from: 'user', time: '10:14', content: 'Why are my steps low this week?' },
{
  from: 'anna', time: '10:14',
  content:
  <div>
        <div>You've averaged <strong style={{ fontWeight: 600 }}>8,420 steps</strong> vs your baseline of 9,200. Three days came in under 7k — all weekdays with 3+ hours of meetings stacked.</div>
        <HBubbleDataCard title="Steps · 14 days" value="8,420" unit="avg" sub="−8% vs baseline"
    chart={<HSparkline data={[9200, 9400, 9100, 7200, 6800, 7100, 8400, 8900, 9100, 7900, 8600, 8200, 8400, 8420]} width={130} height={48} color="var(--focus-fitness)" />} />
        <div style={{ marginTop: 10, fontSize: 14, color: 'var(--t-fg-2)' }}>Two tiny moves can fix this without adding gym time:</div>
        <HNumberedActions items={[
    { title: 'Walking 1:1s on Tuesdays', body: 'You have 3 back-to-back — ~2,500 steps if taken outside.' },
    { title: '8pm post-dinner loop', body: '15 min before TV. Helps BP too.' }]
    } />
      </div>,

  quickReplies: ['Set 8pm reminder', 'Block walking meetings', 'Compare to last month']
}];


const eveningThread = [
{ from: 'anna', time: 'Now',
  content:
  <div>
        Based on your day — meeting-heavy, slight stress, BP creeping up — here's a wind-down sequence for tonight.
        <HNumberedActions items={[
    { title: '8:45pm — phone to night mode', body: 'I\'ll set it. Notifications muted, screen warm.' },
    { title: '9:15pm — 10-min breathwork', body: 'Box breathing. Drops cortisol 12% on average for you.' },
    { title: '10:30pm — in bed by', body: 'Aim for 7h 30m. Wake target: 6:00am.' }]
    } />
      </div>,
  quickReplies: ['Start the breathwork now', 'Move bedtime later', 'What about sleep aids?'] }];


const defaultThread = [
{ from: 'anna', time: 'Now',
  content:
  <div>
        Hi {(window.HEALIFY_USER && window.HEALIFY_USER.first) || 'Kathryn'} — I read through your week. What's on your mind today?
      </div>,
  quickReplies: ['Why is my BP up?', 'Make me a meal plan', 'I slept badly last night', 'Plan my workouts'] }];


Object.assign(window, { ChatScreen });