/**
 * @fileoverview Main entry point for the Messages application
 *
 * This module initializes the Messages app UI, including:
 * - Rendering the navigation bar with the app title or contact name
 * - Displaying either the messages list or a conversation view
 * - Handling navigation between the list and conversation
 *
 * The navigation bar shows "Messages" on the list, and the contact's name with a back button in a conversation.
 */

// Initialize the messages app
function initializeMessagesApp(container) {
    // Get current messages and selected conversation from global state
    const { messages, selectedConversation } = globalState.getState();
    const appContainer = document.createElement('div');

    appContainer.className = 'app-container';
    appContainer.setAttribute('role', 'main');
    appContainer.setAttribute('aria-label', 'Messages');

    /**
     * Navigation bar
     * - Shows "Messages" on the list
     * - Shows contact name and back button in a conversation
     */
    const navBar = new NavigationBar({
        title: selectedConversation ? selectedConversation.contactName : 'Messages',
        showBackButton: !!selectedConversation
    });
    navBar.mount(appContainer);

    // Content container for either the list or conversation
    const contentContainer = document.createElement('div');
    contentContainer.className = 'content';
    appContainer.appendChild(contentContainer);

    /**
     * Render either the conversation view or the messages list
     * - If a conversation is selected, show ConversationView
     * - Otherwise, show MessagesList
     */
    if (selectedConversation) {
        const conversationView = new ConversationView({ conversation: selectedConversation });
        conversationView.mount(contentContainer);
    } else {
        const messagesList = new MessagesList({
            messages,
            onMessageClick: (message) => {
                globalState.setState({ selectedConversation: message });
            }
        });
        messagesList.mount(contentContainer);
    }

    // Mount the app container
    container.appendChild(appContainer);
}

// Make initialization function globally available
window.initializeMessagesApp = initializeMessagesApp;