// Primus IQ — Chat screen components

const ChatMsgBubble = ({ msg }) => {
  const isHuman = msg.role === 'human';
  return (
    <div style={{ display: 'flex', justifyContent: isHuman ? 'flex-end' : 'flex-start', marginBottom: 18 }}>
      {!isHuman && (
        <div style={{
          width: 26, height: 26, borderRadius: 13,
          background: 'var(--maroon)', color: 'white',
          display: 'grid', placeItems: 'center',
          fontSize: 10.5, fontWeight: 700, flexShrink: 0,
          marginRight: 10, marginTop: 2,
        }}>P</div>
      )}
      <div className="chat-msg-bubble-content" style={{
        maxWidth: isHuman ? 500 : 660,
        background: isHuman ? 'var(--maroon)' : 'transparent',
        color: isHuman ? 'white' : 'var(--ink)',
        borderRadius: isHuman ? '14px 14px 4px 14px' : '4px 14px 14px 14px',
        padding: isHuman ? '11px 15px' : '2px 0px',
        fontSize: 14, lineHeight: 1.65,
        border: 'none',
        boxShadow: isHuman ? '0 2px 8px rgba(122,28,28,0.18)' : 'none',
        whiteSpace: 'pre-wrap', wordBreak: 'break-word',
      }}>
        {msg.content}
      </div>
    </div>
  );
};

const ChatThinking = ({ message }) => (
  <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 18 }}>
    <div style={{
      width: 26, height: 26, borderRadius: 13,
      background: 'var(--maroon)', color: 'white',
      display: 'grid', placeItems: 'center',
      fontSize: 10.5, fontWeight: 700, flexShrink: 0, marginRight: 10, marginTop: 2,
    }}>P</div>
    <div style={{
      background: 'transparent', border: 'none',
      borderRadius: '4px 14px 14px 14px',
      padding: '11px 0px', display: 'flex', alignItems: 'center', gap: 9,
    }}>
      <span style={{
        width: 13, height: 13, borderRadius: 999,
        border: '2px solid var(--maroon-20)', borderTopColor: 'var(--maroon)',
        display: 'inline-block', animation: 'pi-spin 0.7s linear infinite', flexShrink: 0,
      }} />
      <span style={{ fontSize: 13, color: 'var(--mute)', fontStyle: 'italic' }}>
        {message || 'Thinking…'}
      </span>
    </div>
  </div>
);

const ChatComposer = ({ onSend, disabled }) => {
  const [val, setVal]       = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const submit = () => { const t = val.trim(); if (!t || disabled) return; setVal(''); onSend(t); };
  const onKD   = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } };
  return (
    <div style={{ padding: '10px 20px 16px', background: 'var(--bg)' }}>
      <div style={{
        background: 'var(--bg-card)', borderRadius: 14,
        border: `1px solid ${focused ? 'var(--maroon-20)' : 'var(--line-2)'}`,
        boxShadow: focused ? '0 0 0 3px var(--maroon-06)' : '0 2px 6px rgba(60,30,20,0.04)',
        transition: 'all 0.18s', padding: '11px 11px 7px 15px',
      }}>
        <textarea
          value={val} onChange={e => setVal(e.target.value)}
          onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
          onKeyDown={onKD} rows={2} disabled={disabled}
          placeholder="Ask Primus IQ…"
          style={{
            width: '100%', border: 'none', resize: 'none', outline: 'none',
            fontFamily: 'inherit', fontSize: 14, color: 'var(--ink)',
            background: 'transparent', lineHeight: 1.5, padding: 0,
            opacity: disabled ? 0.5 : 1,
          }}
        />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8, marginTop: 4 }}>
          <span style={{ fontSize: 11, color: 'var(--mute)' }}>{val.length} / 8,000</span>
          <button onClick={submit} disabled={!val.trim() || disabled} style={{
            width: 32, height: 32, borderRadius: 8,
            background: val.trim() && !disabled ? 'var(--maroon)' : 'var(--bg-soft)',
            color: val.trim() && !disabled ? 'white' : 'var(--mute-2)',
            border: 'none', cursor: val.trim() && !disabled ? 'pointer' : 'default',
            display: 'grid', placeItems: 'center', transition: 'all 0.15s',
          }}>
            <svg width="12" height="12" viewBox="0 0 16 16" fill="none">
              <path d="M8 12V4M4 8l4-4 4 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
      <div style={{ textAlign: 'center', marginTop: 6 }}>
        <span style={{ fontSize: 10.5, color: 'var(--mute-2)' }}>Enter to send · Shift + Enter for new line</span>
      </div>
    </div>
  );
};

const ScreenNewChat = ({ setRoute, openAddSources, currentUser,
                         sessions = [], activeId = null, setActiveId, onSessionsChanged }) => {
  const [messages,    setMessages]    = React.useState([]);
  const [streaming,   setStreaming]   = React.useState(false);
  const [progressMsg, setProgressMsg] = React.useState('');
  const abortRef  = React.useRef(null);
  const bottomRef = React.useRef(null);
  const justCreatedRef = React.useRef(false);

  const hour      = new Date().getHours();
  const greeting  = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';
  const firstName = currentUser?.full_name?.split(' ')?.[0] || 'there';

  React.useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, streaming]);

  React.useEffect(() => {
    if (justCreatedRef.current) { justCreatedRef.current = false; return; }
    if (abortRef.current) { abortRef.current(); abortRef.current = null; }
    setStreaming(false);
    if (!activeId) { setMessages([]); return; }
    PrimusAPI.getChatMessages(activeId)
      .then(data => setMessages(data || []))
      .catch(() => setMessages([]));
  }, [activeId]);

  const handleSend = async (text) => {
    let sessionId = activeId;
    if (!sessionId) {
      try {
        const sess = await PrimusAPI.createChatSession({});
        sessionId = sess.session_id;
        justCreatedRef.current = true;
        setActiveId && setActiveId(sessionId);
        onSessionsChanged && onSessionsChanged();
      } catch (ex) { console.error('Failed to create session:', ex); return; }
    }
    const humanMsg = {
      message_id: `tmp-${Date.now()}`, role: 'human',
      content: text, created_at: new Date().toISOString(),
    };
    setMessages(prev => [...prev, humanMsg]);
    setStreaming(true);
    setProgressMsg('Routing your query…');

    abortRef.current = PrimusAPI.streamChatMessage(sessionId, text, (ev) => {
      if (ev.type === 'progress') {
        setProgressMsg(ev.message || 'Thinking…');
      } else if (ev.type === 'message') {
        setStreaming(false);
        setMessages(prev => [...prev, {
          message_id: ev.message_id || `ai-${Date.now()}`,
          role: 'ai', content: ev.content || '',
          created_at: new Date().toISOString(),
        }]);
      } else if (ev.type === 'done') {
        setStreaming(false);
        onSessionsChanged && onSessionsChanged();
      } else if (ev.type === 'error') {
        setStreaming(false);
        const errMsg = ev.detail || ev.message || 'Please try again.';
        setMessages(prev => [...prev, {
          message_id: `err-${Date.now()}`, role: 'ai',
          content: `Something went wrong: ${errMsg}`,
          created_at: new Date().toISOString(),
        }]);
      }
    });
  };

  const activeSession = sessions.find(s => s.session_id === activeId) || null;

  if (activeId) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0, background: 'var(--bg)' }}>
        <div style={{
          padding: '13px 24px', borderBottom: '1px solid var(--line)',
          background: 'var(--bg-card)', flexShrink: 0, display: 'flex', alignItems: 'center',
        }}>
          <span style={{
            fontSize: 14, fontWeight: 600, color: 'var(--ink)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {activeSession?.title || 'Chat'}
          </span>
        </div>
        <div className="pi-thin-scroll" style={{ flex: 1, overflowY: 'auto', padding: '24px 0 0' }}>
          <div style={{ maxWidth: 760, margin: '0 auto', padding: '0 24px' }}>
            {messages.map((m, i) => <ChatMsgBubble key={m.message_id || i} msg={m} />)}
            {streaming && <ChatThinking message={progressMsg} />}
            <div ref={bottomRef} />
          </div>
        </div>
        <div style={{ maxWidth: 760, margin: '0 auto', width: '100%' }}>
          <ChatComposer onSend={handleSend} disabled={streaming} />
        </div>
      </div>
    );
  }

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', height: '100%',
      alignItems: 'center', justifyContent: 'center',
      padding: '0 48px', minWidth: 0, background: 'var(--bg)',
    }}>
      <h1 className="serif" style={{
        fontSize: 28, fontWeight: 400, margin: 0, marginBottom: 36,
        letterSpacing: '-0.025em', lineHeight: 1.05, textAlign: 'center',
      }}>
        <span style={{ color: 'var(--mute)' }}>{greeting},</span>{' '}
        <span className="wordmark">{firstName}</span>
      </h1>
      <div style={{ width: 680, maxWidth: '100%' }}>
        <ChatComposer onSend={handleSend} disabled={false} />
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center', marginTop: 12 }}>
        {[
          { l: 'Summarize a project',    icon: 'folder' },
          { l: 'Draft an RFP response',  icon: 'apps'   },
          { l: 'Find an old whitepaper', icon: 'search' },
          { l: 'Research market trends', icon: 'book'   },
        ].map(c => (
          <button key={c.l} onClick={() => handleSend(c.l)} style={chipBtn}>
            <PIcon name={c.icon} size={14} color="var(--maroon)" />
            {c.l}
          </button>
        ))}
      </div>
    </div>
  );
};

const composerIconBtn = {
  width: 32, height: 32, borderRadius: 8,
  background: 'transparent', border: '1px solid var(--line-2)',
  cursor: 'pointer', display: 'grid', placeItems: 'center',
  transition: 'all 0.15s',
};
const composerChip = {
  height: 32, padding: '0 10px', borderRadius: 8,
  background: 'transparent', border: '1px solid var(--line-2)',
  cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
  fontSize: 13, color: 'var(--ink-2)', fontFamily: 'inherit', fontWeight: 500,
};
const chipBtn = {
  padding: '8px 14px', borderRadius: 999,
  background: 'var(--bg-card)', border: '1px solid var(--line)',
  fontSize: 13, color: 'var(--ink-2)', fontFamily: 'inherit', fontWeight: 500,
  cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6,
  transition: 'all 0.15s',
};

Object.assign(window, {
  ChatMsgBubble,
  ChatThinking,
  ChatComposer,
  ScreenNewChat,
  composerIconBtn,
  composerChip,
  chipBtn,
});
