// Live Chat screen — mock support conversation UI

function LiveChatScreen({ theme, accent, onBack }) {
  const [input, setInput] = React.useState('');
  const [messages, setMessages] = React.useState(LIVE_CHAT_MESSAGES);
  const bottomRef = React.useRef(null);

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

  function handleSend() {
    const text = input.trim();
    if (!text) return;
    const now = new Date();
    const time = now.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
    setMessages(prev => [...prev, { id: Date.now(), from: 'user', text, time }]);
    setInput('');
    // Mock agent typing response after short delay
    setTimeout(() => {
      setMessages(prev => [...prev, {
        id: Date.now() + 1,
        from: 'agent',
        name: 'Sara — Himma Support',
        text: 'Thanks for your message! Let me look into that for you and get back to you shortly. 😊',
        time: new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' }),
      }]);
    }, 1200);
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); }
  }

  return (
    <Screen theme={theme} padTop={0} padBottom={0}>
      {/* Header */}
      <NavBar theme={theme} title="Live chat" onBack={onBack}/>

      {/* Agent status bar */}
      <div style={{
        margin: '0 16px 2px',
        padding: '10px 14px',
        background: theme.surface,
        border: `0.5px solid ${theme.line2}`,
        borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        {/* Avatar */}
        <div style={{
          width: 34, height: 34, borderRadius: 17,
          background: `${accent}1A`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0, position: 'relative',
        }}>
          <span style={{ fontSize: 16 }}>👩‍💼</span>
          {/* Online dot */}
          <div style={{
            position: 'absolute', bottom: 0, right: 0,
            width: 9, height: 9, borderRadius: 5,
            background: '#3DBD6E',
            border: `1.5px solid ${theme.bg}`,
          }}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: theme.text, fontFamily: FONTS.ui }}>Sara</div>
          <div style={{ fontSize: 11, color: theme.textDim, marginTop: 1 }}>Himma Support · Online</div>
        </div>
        <div style={{
          fontFamily: FONTS.mono, fontSize: 10, color: accent,
          background: `${accent}14`, borderRadius: 8, padding: '3px 8px',
        }}>Live</div>
      </div>

      {/* Message list */}
      <div style={{
        flex: 1,
        overflowY: 'auto',
        padding: '12px 16px',
        display: 'flex', flexDirection: 'column', gap: 10,
        minHeight: 0,
        maxHeight: 380,
      }}>
        {/* Date chip */}
        <div style={{ textAlign: 'center' }}>
          <span style={{
            fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute,
            background: theme.surface, border: `0.5px solid ${theme.line2}`,
            borderRadius: 8, padding: '3px 10px',
          }}>Today</span>
        </div>

        {messages.map((msg, i) => {
          const isUser = msg.from === 'user';
          const prevSameFrom = i > 0 && messages[i - 1].from === msg.from;
          const lines = msg.text.split('\n');
          return (
            <div key={msg.id} style={{
              display: 'flex',
              flexDirection: isUser ? 'row-reverse' : 'row',
              alignItems: 'flex-end',
              gap: 6,
              marginTop: prevSameFrom ? 2 : 6,
            }}>
              {/* Agent avatar — only show on first in group */}
              {!isUser && (
                <div style={{
                  width: 26, height: 26, borderRadius: 13,
                  background: `${accent}1A`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                  opacity: prevSameFrom ? 0 : 1,
                }}>
                  <span style={{ fontSize: 13 }}>👩‍💼</span>
                </div>
              )}

              <div style={{ maxWidth: '76%', display: 'flex', flexDirection: 'column', alignItems: isUser ? 'flex-end' : 'flex-start' }}>
                {/* Bubble */}
                <div style={{
                  background: isUser ? theme.text : theme.surface,
                  color: isUser ? theme.bg : theme.text,
                  border: isUser ? 'none' : `0.5px solid ${theme.line2}`,
                  borderRadius: isUser ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
                  padding: '9px 13px',
                  fontSize: 13,
                  fontFamily: FONTS.ui,
                  lineHeight: 1.5,
                }}>
                  {lines.map((line, li) => (
                    <span key={li}>{line}{li < lines.length - 1 && <><br/><br/></>}</span>
                  ))}
                </div>
                {/* Time */}
                <div style={{
                  fontSize: 10, color: theme.textMute, fontFamily: FONTS.mono,
                  marginTop: 3, paddingLeft: isUser ? 0 : 2, paddingRight: isUser ? 2 : 0,
                }}>{msg.time}</div>
              </div>
            </div>
          );
        })}
        <div ref={bottomRef}/>
      </div>

      {/* Input bar */}
      <div style={{
        padding: '10px 16px 12px',
        borderTop: `0.5px solid ${theme.line}`,
        display: 'flex', alignItems: 'flex-end', gap: 10,
      }}>
        <div style={{
          flex: 1,
          background: theme.surface,
          border: `0.5px solid ${theme.line2}`,
          borderRadius: 20,
          padding: '10px 14px',
          display: 'flex', alignItems: 'center',
        }}>
          <textarea
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Type a message…"
            rows={1}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              resize: 'none', color: theme.text, fontFamily: FONTS.ui, fontSize: 13,
              lineHeight: 1.5,
            }}
          />
        </div>
        <button
          onClick={handleSend}
          style={{
            width: 38, height: 38, borderRadius: 19, flexShrink: 0,
            background: input.trim() ? theme.text : theme.surface2,
            border: `0.5px solid ${input.trim() ? theme.text : theme.line2}`,
            color: input.trim() ? theme.bg : theme.textMute,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: input.trim() ? 'pointer' : 'default',
            transition: 'background 140ms, color 140ms',
          }}
        >
          <Ico.send size={15} stroke="currentColor"/>
        </button>
      </div>
    </Screen>
  );
}

Object.assign(window, { LiveChatScreen });
