function AICopilot() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState([
    { role: 'assistant', content: 'สวัสดีครับ! ผมคือ AI ผู้เชี่ยวชาญด้าน Meta Ads ผมสามารถดึงข้อมูลแคมเปญของคุณมาวิเคราะห์ให้ได้ คุณอยากทราบอะไรเกี่ยวกับโฆษณาของคุณบ้างครับ?' }
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef(null);

  // Auto-scroll
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, isOpen]);

  const META_TOOLS = [
    {
      type: 'function',
      function: {
        name: 'get_meta_dashboard',
        description: 'Fetch the 7-day performance dashboard and placement breakdown from Meta Ads API. Use this when user asks about overall spend, revenue, ROAS, or placement performance.',
        parameters: { type: 'object', properties: {} }
      }
    },
    {
      type: 'function',
      function: {
        name: 'get_meta_campaigns',
        description: 'Fetch the list of active campaigns and their performance (spend, roas, conversions, cpc, ctr) from Meta Ads API. Use this when the user asks about specific campaigns or wants a breakdown by campaign.',
        parameters: { type: 'object', properties: {} }
      }
    }
  ];

  const handleSend = async () => {
    if (!input.trim() || loading) return;
    
    const userMsg = { role: 'user', content: input.trim() };
    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput('');
    setLoading(true);

    try {
      // call aiChatWithTools which handles tool execution autonomously
      const finalMsgs = await aiChatWithTools(
        [
          { role: 'system', content: 'คุณเป็น AI ผู้เชี่ยวชาญด้าน Meta Ads (Data Analyst) ของแบรนด์ Earthlab. ตอบเป็นภาษาไทย ให้คำแนะนำที่เป็นประโยชน์. หากข้อมูลยาวให้จัดรูปแบบเป็น Bullet points. คุณมีเครื่องมือในการดึงข้อมูลจาก Meta Ads API.' },
          ...newMessages
        ], 
        META_TOOLS
      );

      // finalMsgs contains system, user, tool, and assistant messages.
      // we only want to display user and assistant content messages in the UI
      // filter out system and tool messages
      const displayMsgs = finalMsgs.filter(m => 
        (m.role === 'user' || m.role === 'assistant') && 
        (typeof m.content === 'string' && m.content.length > 0)
      );

      // the displayMsgs includes the system prompt at index 0. Let's slice it out and prepend the initial greeting.
      // Wait, finalMsgs has the system prompt at [0].
      const filtered = finalMsgs.filter(m => m.role !== 'system' && m.role !== 'tool' && !m.tool_calls);
      
      // Merge with the first greeting message
      setMessages([messages[0], ...filtered]);
    } catch (err) {
      setMessages(prev => [...prev, { role: 'assistant', content: `เกิดข้อผิดพลาด: ${err.message}` }]);
    }
    
    setLoading(false);
  };

  if (!isOpen) {
    return (
      <button 
        onClick={() => setIsOpen(true)}
        className="fade-up"
        style={{
          position: 'fixed', bottom: 24, right: 24, zIndex: 999,
          width: 56, height: 56, borderRadius: '50%',
          background: 'var(--accent)', color: 'var(--surface)',
          border: 'none', cursor: 'pointer',
          boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'transform 0.2s cubic-bezier(.4,0,.2,1)'
        }}
        onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.05)'}
        onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
      >
        <IconSpark size={24} />
      </button>
    );
  }

  return (
    <div 
      className="fade-up"
      style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 999,
        width: 360, height: 500,
        background: 'var(--surface)', borderRadius: 'var(--radius)',
        boxShadow: '0 12px 40px rgba(0,0,0,0.15), 0 0 0 1px var(--border)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden'
      }}
    >
      {/* Header */}
      <div style={{
        padding: '16px 20px', background: 'var(--accent)', color: 'var(--surface)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <IconSpark size={18} />
          <span style={{ fontWeight: 700, fontSize: 14.5 }}>AI Copilot</span>
        </div>
        <button onClick={() => setIsOpen(false)} style={{
          background: 'transparent', border: 'none', color: 'var(--surface)',
          cursor: 'pointer', padding: 4, display: 'grid', placeItems: 'center', opacity: 0.8
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
      </div>

      {/* Messages */}
      <div style={{ flex: 1, padding: 16, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 16, background: 'var(--surface-2)' }}>
        {messages.map((m, i) => {
          const isUser = m.role === 'user';
          return (
            <div key={i} style={{ display: 'flex', justifyContent: isUser ? 'flex-end' : 'flex-start' }}>
              {!isUser && (
                <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--accent)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginRight: 8, marginTop: 4 }}>
                  <IconSpark size={14} />
                </div>
              )}
              <div style={{
                maxWidth: '80%', padding: '10px 14px', borderRadius: 16, fontSize: 13.5, lineHeight: 1.55,
                background: isUser ? 'var(--accent)' : 'var(--surface)',
                color: isUser ? 'white' : 'var(--ink)',
                border: isUser ? 'none' : '1px solid var(--border)',
                borderTopRightRadius: isUser ? 4 : 16,
                borderTopLeftRadius: !isUser ? 4 : 16,
                whiteSpace: 'pre-wrap'
              }}>
                {m.content}
              </div>
            </div>
          );
        })}
        {loading && (
          <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--accent)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginRight: 8, marginTop: 4 }}>
              <IconSpark size={14} />
            </div>
            <div style={{
              padding: '10px 16px', borderRadius: 16, fontSize: 13.5, background: 'var(--surface)', color: 'var(--ink-2)', border: '1px solid var(--border)', borderTopLeftRadius: 4, display: 'flex', gap: 6, alignItems: 'center'
            }}>
              <IconRefresh size={14} className="spin" style={{ color: 'var(--accent)' }} /> 
              กำลังประมวลผลและดึงข้อมูล...
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      <div style={{ padding: 12, background: 'var(--surface)', borderTop: '1px solid var(--border)' }}>
        <form onSubmit={e => { e.preventDefault(); handleSend(); }} style={{ display: 'flex', gap: 8 }}>
          <input
            type="text"
            value={input}
            onChange={e => setInput(e.target.value)}
            placeholder="ถามเกี่ยวกับโฆษณาของคุณ..."
            disabled={loading}
            style={{
              flex: 1, padding: '10px 14px', borderRadius: 20, border: '1px solid var(--border-2)',
              background: 'var(--surface-2)', fontSize: 13.5, fontFamily: 'inherit', color: 'var(--ink)'
            }}
          />
          <button type="submit" disabled={!input.trim() || loading} style={{
            width: 40, height: 40, borderRadius: '50%', background: input.trim() && !loading ? 'var(--accent)' : 'var(--surface-3)',
            color: input.trim() && !loading ? 'white' : 'var(--ink-3)', border: 'none', cursor: input.trim() && !loading ? 'pointer' : 'default',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'all 0.2s'
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
          </button>
        </form>
      </div>
    </div>
  );
}
