// Ask tab — chat against /api/chat. Empty state with suggestion pills,
// user (right blue bubble) / assistant (left white card) bubbles, pulsing
// "analyzing…" loader, sticky rounded input pill at the bottom.

const { api: askApi } = window.HC_DATA;

function AskTab() {
  const theme = window.HC_THEME.useHCTheme();
  const p = theme.palette;
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  const suggestions = [
    'what happened this week',
    'how are drinks affecting my sleep',
    'am I ready to train again',
    'compare this week to last week',
  ];

  // Heuristic: questions that span longer windows should pull more history.
  function inferDays(q) {
    const t = q.toLowerCase();
    if (/since (jan|feb|march|april|new year)|month|year/.test(t)) return 150;
    if (/last 4 weeks|past month/.test(t)) return 30;
    return 14;
  }

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || loading) return;
    setInput('');
    const next = [...messages, { role: 'user', content: q }];
    setMessages(next);
    setLoading(true);
    try {
      const res = await askApi('/api/chat', {
        method: 'POST',
        body: JSON.stringify({
          message: q,
          history: next.slice(0, -1),
          days: inferDays(q),
        }),
      });
      setMessages([...next, { role: 'assistant', content: res.reply || '' }]);
    } catch (e) {
      setMessages([...next, {
        role: 'assistant',
        content: "— couldn't reach the analyst. try again.",
      }]);
    } finally { setLoading(false); }
  };

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

  const hasConversation = messages.length > 0 || loading;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: 540, padding: '0 16px 0' }}>

      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', paddingBottom: 16,
        display: 'flex', flexDirection: 'column',
        justifyContent: hasConversation ? 'flex-start' : 'center',
        gap: 10, minHeight: 460,
      }}>
        {!hasConversation && (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22, marginTop: 30 }}>
            <div style={{
              fontFamily: 'DM Mono, monospace', fontSize: 16, color: p.text3,
              letterSpacing: 0.3,
            }}>ask anything</div>
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, width: '100%',
            }}>
              {suggestions.map((s) => (
                <button key={s} onClick={() => send(s)} style={{
                  padding: '12px 10px', textAlign: 'left',
                  fontFamily: 'DM Mono, monospace', fontSize: 11,
                  color: p.text2, lineHeight: 1.35,
                  background: p.card, border: `1px solid ${p.border}`,
                  borderRadius: 10, cursor: 'pointer',
                }}>{s}</button>
              ))}
            </div>
          </div>
        )}

        {messages.map((m, i) => (
          m.role === 'user' ? (
            <div key={i} style={{ alignSelf: 'flex-end', maxWidth: '82%' }}>
              <div style={{
                background: p.accent, color: '#fff',
                fontFamily: 'DM Sans', fontSize: 14, lineHeight: 1.45,
                padding: '9px 13px', borderRadius: '14px 14px 4px 14px',
                whiteSpace: 'pre-wrap',
              }}>{m.content}</div>
            </div>
          ) : (
            <div key={i} style={{ width: '100%' }}>
              <div style={{
                background: p.card, border: `1px solid ${p.border}`,
                fontFamily: 'DM Sans', fontSize: 14, lineHeight: 1.55, color: p.text,
                padding: '12px 14px', borderRadius: 12,
                whiteSpace: 'pre-wrap',
              }}>{m.content}</div>
            </div>
          )
        ))}

        {loading && (
          <div style={{
            fontFamily: 'DM Mono, monospace', fontSize: 12, color: p.text3,
            padding: '6px 4px', animation: 'hc-pulse 1.2s ease-in-out infinite',
          }}>analyzing…</div>
        )}
      </div>

      <div style={{
        position: 'sticky', bottom: 0,
        padding: '10px 0 16px',
        background: `linear-gradient(to bottom, ${p.bg}00, ${p.bg} 30%)`,
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: p.inputBg, border: `1px solid ${p.border}`,
          borderRadius: 22, padding: '4px 4px 4px 14px',
        }}>
          <input value={input} onChange={(e) => setInput(e.target.value)}
                 onKeyDown={onKey} placeholder="ask about your data"
                 style={{
                   flex: 1, border: 'none', background: 'transparent', outline: 'none',
                   fontFamily: 'DM Sans', fontSize: 14, color: p.text,
                   padding: '8px 0',
                 }} />
          <button onClick={() => send()} disabled={!input.trim() || loading} style={{
            width: 34, height: 34, borderRadius: '50%', border: 'none',
            background: input.trim() && !loading ? p.accent : p.border,
            color: '#fff', cursor: input.trim() && !loading ? 'pointer' : 'default',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M7 11.5V2.5M3 6.5L7 2.5L11 6.5"
                    stroke="currentColor" strokeWidth="1.8"
                    strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </div>
      </div>

      <style>{`@keyframes hc-pulse { 0%,100% { opacity: 0.5 } 50% { opacity: 1 } }`}</style>
    </div>
  );
}

window.AskTab = AskTab;
