/* Jane chatbot — redesigned to match the new system */
(function(){
function ChatButton() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { text: "Hi! I'm Jane, your AI assistant. How can I help you today?", isUser: false }
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const inputRef = React.useRef(null);
  const endRef = React.useRef(null);

  React.useEffect(() => {
    const open = () => setOpen(true);
    window.addEventListener('openChat', open);
    return () => window.removeEventListener('openChat', open);
  }, []);
  React.useEffect(() => { endRef.current?.scrollIntoView({behavior:'smooth'}); }, [messages, loading]);

  const send = async () => {
    if (!input.trim() || loading) return;
    const userMsg = input;
    setMessages(m => [...m, { text: userMsg, isUser: true }]);
    setInput('');
    setLoading(true);
    try {
      const r = await fetch('https://n8n.jane.iternative.com/webhook/ITernative_Chathook', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: userMsg, timestamp: new Date().toISOString(), session_id: 'preview-' + Date.now() })
      });
      const data = await r.json();
      const text = data.output || data.response || data.message || 'I received your message.';
      setMessages(m => [...m, { text, isUser: false }]);
    } catch {
      setMessages(m => [...m, { text: 'Sorry, I encountered an error. Please try again.', isUser: false }]);
    } finally {
      setLoading(false);
      setTimeout(()=>inputRef.current?.focus(), 50);
    }
  };

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

  return (
    <>
      <button className={`chat-fab ${open ? 'open' : ''}`} onClick={()=>setOpen(o=>!o)} aria-label="Chat with Jane">
        {open ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
        )}
        {!open && <span className="chat-fab-pulse" aria-hidden="true"></span>}
      </button>
      {open && (
        <div className="chat-window panel">
          <div className="chat-header">
            <div className="chat-id">
              <span className="status-dot" aria-hidden="true"></span>
              <div>
                <div className="chat-name">Jane</div>
                <div className="mono fog" style={{fontSize:10, letterSpacing:'0.15em', textTransform:'uppercase'}}>AI Assistant · Online</div>
              </div>
            </div>
            <button className="chat-x" onClick={()=>setOpen(false)} aria-label="Close">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>
          <div className="chat-msgs">
            {messages.map((m,i)=>(
              <div key={i} className={`chat-msg ${m.isUser ? 'user' : 'bot'}`}>
                {!m.isUser && <div className="chat-avatar">J</div>}
                <div className="chat-bubble">{m.text}</div>
              </div>
            ))}
            {loading && (
              <div className="chat-msg bot">
                <div className="chat-avatar">J</div>
                <div className="chat-bubble"><span className="chat-typing"><i></i><i></i><i></i></span></div>
              </div>
            )}
            <div ref={endRef}/>
          </div>
          <div className="chat-input">
            <input ref={inputRef} autoFocus value={input} onChange={e=>setInput(e.target.value)} onKeyDown={keyDown} placeholder="Type your message..." disabled={loading} />
            <button onClick={send} disabled={loading || !input.trim()} aria-label="Send">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
            </button>
          </div>
        </div>
      )}
    </>
  );
}
window.ChatButton = ChatButton;
})();
