<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">
    <title>SMS Messenger</title>
    <style>
        :root {
            --primary-color: #0084ff;
            --secondary-color: #f0f2f5;
            --unread-indicator: #00c853;
            --text-primary: #050505;
            --text-secondary: #65676b;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
        }

        body {
            background: #ffffff;
        }

        .container {
            display: grid;
            grid-template-columns: minmax(260px, 300px) 1fr;
            height: 100vh;
            position: relative;
        }

        /* Senders List Styles */
        .senders-list {
            background: #ffffff;
            border-right: 1px solid rgba(0,0,0,0.08);
            overflow-y: auto;
            position: relative;
        }

        .sender-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            cursor: pointer;
            transition: background 0.2s;
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }

        .sender-item:hover {
            background: var(--secondary-color);
        }

        .sender-unread {
            background: #f5f9ff;
            position: relative;
        }

        .sender-info {
            margin-left: 16px;
            flex-grow: 1;
            min-width: 0;
        }

        .sender-name {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .sender-address {
            font-size: 0.875rem;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .unread-badge {
            background: var(--unread-indicator);
            color: white;
            padding: 4px 8px;
            border-radius: 16px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-left: auto;
        }

        /* Messages Container Styles */
        .messages-container {
            display: flex;
            flex-direction: column;
            background: var(--secondary-color);
            position: relative;
        }

        .messages-header {
            background: #ffffff;
            padding: 16px;
            border-bottom: 1px solid rgba(0,0,0,0.08);
            display: flex;
            align-items: center;
        }

        .messages-scroll {
            flex-grow: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .message-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            background: #ffffff;
            position: relative;
            box-shadow: 0 1px 3px rgba(0,0,0,0.08);
            animation: messageAppear 0.3s ease;
        }

        .message-bubble.unread {
            background: #e3f2fd;
            border-left: 4px solid var(--primary-color);
        }

        .message-time {
            font-size: 0.75rem;
            color: var(--text-secondary);
            margin-top: 6px;
            text-align: right;
        }

        .message-status {
            position: absolute;
            bottom: 4px;
            right: 8px;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .typing-indicator {
            padding: 16px;
            font-size: 0.9rem;
            color: var(--text-secondary);
            display: none;
        }

        @keyframes messageAppear {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Mobile Styles */
        @media (max-width: 768px) {
            .container {
                grid-template-columns: 1fr;
                grid-template-rows: auto 1fr;
            }

            .senders-list {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                z-index: 100;
                background: white;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }

            .senders-list.active {
                transform: translateX(0);
            }

            .messages-container {
                transform: translateX(0);
            }

            .back-button {
                display: inline-flex;
                align-items: center;
                gap: 8px;
                padding: 8px 16px;
                background: none;
                border: none;
                color: var(--primary-color);
                font-weight: 500;
            }
        }

        /* Loading States */
        .loading-state {
            display: flex;
            justify-content: center;
            padding: 24px;
            color: var(--text-secondary);
        }

        .loading-spinner {
            width: 24px;
            height: 24px;
            border: 3px solid rgba(0,0,0,0.1);
            border-top-color: var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="senders-list" id="sendersList"></div>
        <div class="messages-container" id="messagesContainer">
            <div class="messages-header">
                <button class="back-button" onclick="showSendersList()">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z"/>
                    </svg>
                    Back
                </button>
            </div>
            <div class="messages-scroll" id="messagesScroll"></div>
            <div class="typing-indicator" id="typingIndicator"></div>
        </div>
    </div>

    <script>
        // Modernized JavaScript with better state management
        let currentSender = null;
        const sendersList = document.getElementById('sendersList');
        const messagesScroll = document.getElementById('messagesScroll');
        
        document.addEventListener('DOMContentLoaded', async () => {
            const companyId = sessionStorage.getItem('companyId');
            const branchId = sessionStorage.getItem('branchId');
            
            if (!companyId || !branchId) {
                showError('Company or Branch not set in session.');
                return;
            }

            showLoading(sendersList);
            try {
                await RequestNewMessages(companyId, branchId);
                await loadSenders();
            } catch (error) {
                showError('Failed to load messages');
            } finally {
                hideLoading();
            }
        });

        async function loadMessages(senderId) {
            currentSender = senderId;
            showLoading(messagesScroll);
            try {
                const response = await fetch(`/api/sms/sender/${encodeURIComponent(senderId)}`);
                const messages = await response.json();
                
                messagesScroll.innerHTML = messages.map(message => `
                    <div class="message-bubble ${!message.view ? 'unread' : ''}">
                        <div class="message-text">${message.amount.toLocaleString()}</div>
                        <div class="message-time">
                            ${new Date(message.date).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </div>
                    </div>
                `).join('');
                
                if (window.innerWidth <= 768) {
                    sendersList.classList.remove('active');
                    messagesContainer.classList.add('active');
                }
                
                messagesScroll.scrollTop = messagesScroll.scrollHeight;
            } catch (error) {
                showError('Failed to load messages');
            } finally {
                hideLoading();
            }
        }

        function showSendersList() {
            if (window.innerWidth <= 768) {
                sendersList.classList.add('active');
                messagesContainer.classList.remove('active');
            }
        }

        // Modern UI Helpers
        function showLoading(element) {
            element.innerHTML = `
                <div class="loading-state">
                    <div class="loading-spinner"></div>
                </div>
            `;
        }

        function hideLoading() {
            document.querySelectorAll('.loading-state').forEach(el => el.remove());
        }

        function showError(message) {
            const alert = document.createElement('div');
            alert.className = 'error-message';
            alert.textContent = message;
            document.body.appendChild(alert);
            setTimeout(() => alert.remove(), 3000);
        }


        async function loadSenders() {
            try {
                const response = await fetch('/api/sms/senders');
                const senders = await response.json();
                
                const sendersList = document.getElementById('sendersList');
                sendersList.innerHTML = senders.map(sender => `
                    <div class="sender-item ${sender.unreadCount > 0 ? 'sender-unread' : ''}" 
                         onclick="loadMessages('${sender._id}')">
                        <div style="font-weight: 500;">${sender._id}</div>
                        <div style="font-size: 0.9em; color: #666;">${sender.address}</div>
                        ${sender.unreadCount > 0 ? `
                        <div style="margin-top: 0.5rem;">
                            <span class="unread-badge">${sender.unreadCount} unread</span>
                        </div>` : ''}
                    </div>
                `).join('');
            } catch (error) {
                console.error('Error loading senders:', error);
            }
        }

        async function RequestNewMessages(companyId, branchId) {
            try {
                const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
                const data = await response.json();
                const defaultSmsUserId = data.defaultSmsUserId; // defaults
                const response2 = await fetch(`/api/sms/sendRequest/${defaultSmsUserId}`);
                if (response2.ok) {
                    console.log("request sent successfully");
                }
            } catch (error) {
                console.error('Error requesting new messages:', error);
            }
        }
        // Rest of your existing API functions...
    </script>
</body>
</html>