Implement a chat feature in an existing application.
For this coding exercise, convert a flat list of messages into conversation state for the active user. Return each conversation's messages in chronological order and conversations ordered by their latest message.
Use build_chat_state(messages, current_user_id), where each message contains id, conversation_id, sender_id, text, timestamp, and is_read; return dictionaries containing conversation_id, messages, and unread_count.
def build_chat_state(messages, current_user_id):