// ChatScreen.jsx — primary surface; user can send messages, get a fake reply
function ChatScreen({ onBack }) {
  const [messages, setMessages] = React.useState([
    { from: 'ax', kind: 'time', text: 'Today · 08:14' },
    { from: 'ax', text: 'Your sleep average dropped 0.4 hours this week.', chips: [
        { variant: 'accent', label: '−0.4h avg' }, { variant: 'default', label: 'sleep' },
    ]},
    { from: 'me', text: 'Why do you think that is?' },
    { from: 'ax', text: 'A few things line up. On Tue and Wed, dinner was after 21:00 and sleep onset was ~40 min later than your baseline.', continued: true },
    { from: 'ax', text: 'Nothing conclusive yet — a 14-day experiment on "dinner before 19:00" would show whether it\'s the cause. Interested?',
      actions: [{ label: 'Set up experiment', variant: 'primary' }, { label: 'Tell me more', variant: 'secondary' }] },
  ]);
  const [draft, setDraft] = React.useState('');
  const [streaming, setStreaming] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, streaming]);

  const send = () => {
    const txt = draft.trim();
    if (!txt) return;
    setMessages(m => [...m, { from: 'me', text: txt }]);
    setDraft('');
    setStreaming(true);
    setTimeout(() => {
      setStreaming(false);
      setMessages(m => [...m, {
        from: 'ax',
        text: 'I hear you. Want me to pull together what we know about that, or should we start a small experiment first?',
      }]);
    }, 1100);
  };

  return (
    <div style={{ background: M.canvas, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{
        padding: '4px 16px 14px', borderBottom: `1px solid ${M.rule}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: M.canvas,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <DSAxisAvatar size={26} radius={7} />
          <div>
            <div style={{ font: `500 15px/1.1 ${M.sans}`, color: M.ink }}>Axis</div>
            <div style={{ font: `400 11px/1.1 ${M.sans}`, color: M.inkMuted, marginTop: 2 }}>
              {streaming ? 'Thinking with you…' : 'Thinking with you · ready'}
            </div>
          </div>
        </div>
        <DSChip variant="default" style={{ padding: '4px 8px', fontSize: 11 }}>
          <MStatusDot color={M.success} /> Insight Seeker
        </DSChip>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto',
        padding: '18px 16px 16px',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        {messages.map((m, i) => {
          if (m.kind === 'time') return (
            <div key={i} style={{ alignSelf: 'center', font: `500 10px/1 ${M.sans}`, color: M.inkFaint, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
              {m.text}
            </div>
          );
          if (m.from === 'ax') return (
            <div key={i} style={{
              maxWidth: 300, background: M.surface, border: `1px solid ${M.rule}`,
              borderRadius: 14, borderTopLeftRadius: 4, padding: '12px 14px',
              font: `400 15px/1.5 ${M.sans}`, color: M.ink,
            }}>
              {m.text.split(/(\d+\.?\d*\s?h(?:ours)?|\d+(?:\.\d+)?(?:\sh|h\b))/g).map((part, j) =>
                /\d/.test(part) && /h/.test(part) ? <b key={j} style={{ fontWeight: 500 }}>{part}</b> : part
              )}
              {m.chips && (
                <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
                  {m.chips.map((c, k) => (
                    <DSChip key={k} variant={c.variant} style={{ padding: '4px 8px', fontSize: 11 }}>{c.label}</DSChip>
                  ))}
                </div>
              )}
              {m.actions && (
                <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
                  {m.actions.map((a, k) => (
                    <DSButton key={k} size="sm" variant={a.variant} style={{ borderRadius: 8, padding: '6px 10px', fontSize: 12 }}>
                      {a.label}
                    </DSButton>
                  ))}
                </div>
              )}
              {m.continued && (
                <div style={{ font: `400 12px/1 ${M.sans}`, color: M.inkFaint, marginTop: 8, fontStyle: 'italic' }}>continued…</div>
              )}
            </div>
          );
          return (
            <div key={i} style={{
              alignSelf: 'flex-end', maxWidth: 260,
              background: M.axis, color: '#fff',
              borderRadius: 14, borderTopRightRadius: 4,
              padding: '12px 14px', font: `400 15px/1.5 ${M.sans}`,
            }}>{m.text}</div>
          );
        })}
        {streaming && (
          <div style={{
            maxWidth: 80, background: M.surface, border: `1px solid ${M.rule}`,
            borderRadius: 14, borderTopLeftRadius: 4, padding: '14px',
            display: 'flex', gap: 4,
          }}>
            {[0,1,2].map(d => <div key={d} style={{
              width: 5, height: 5, borderRadius: 999, background: M.inkMuted,
              animation: `mPulse 1s ${d*0.15}s infinite ease-in-out`,
            }}/>)}
            <style>{`@keyframes mPulse { 0%,80%,100% { opacity: .25 } 40% { opacity: 1 } }`}</style>
          </div>
        )}
      </div>

      {/* Disclaimer bar */}
      <DSMedicalDisclaimer length="compact" />

      {/* Composer */}
      <div style={{ padding: '10px 12px 16px', background: M.canvas, borderTop: `1px solid ${M.rule}` }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: M.surface, border: `1px solid ${M.rule}`,
          borderRadius: 999, padding: '6px 6px 6px 16px',
        }}>
          <input
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
            placeholder="Ask Axis…"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              font: `400 15px/1.2 ${M.sans}`, color: M.ink,
            }}
          />
          <button onClick={send} disabled={!draft.trim()} style={{
            width: 32, height: 32, borderRadius: 999,
            background: draft.trim() ? M.axis : M.inkFaint,
            border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: draft.trim() ? 'pointer' : 'default',
            transition: 'background 120ms cubic-bezier(.2,.8,.2,1)',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <path d="M4 12h14M13 6l6 6-6 6" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

window.ChatScreen = ChatScreen;
