            </div><!-- End Content -->
        </main>
    </div><!-- End Wrapper -->
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script>
        // Global variables
        const SITE_URL = '<?= SITE_URL ?>';
        const API_URL = '<?= API_URL ?>';
        const CURRENCY_SYMBOL = '<?= CURRENCY_SYMBOL ?>';
        const USER_ID = <?= $user['id'] ?>;
        
        // Sidebar Toggle
        document.getElementById('sidebarToggle')?.addEventListener('click', () => {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('sidebarOverlay').classList.toggle('active');
        });
        
        // User Dropdown
        function toggleUserDropdown() {
            document.getElementById('userDropdown').classList.toggle('active');
        }
        
        function toggleNotifications() {
            // TODO: Show notifications dropdown
            window.location.href = 'notifications.php';
        }
        
        // Close dropdowns on outside click
        document.addEventListener('click', (e) => {
            const dropdown = document.getElementById('userDropdown');
            if (dropdown && !dropdown.contains(e.target)) {
                dropdown.classList.remove('active');
            }
        });
        
        // Format currency
        function formatCurrency(amount) {
            return CURRENCY_SYMBOL + parseFloat(amount).toLocaleString('en-IN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
        
        // Show toast notification
        function showToast(message, type = 'success') {
            const toast = document.createElement('div');
            toast.className = `alert alert-${type === 'error' ? 'danger' : type}`;
            toast.style.cssText = 'position: fixed; top: 80px; right: 20px; z-index: 9999; min-width: 300px; animation: slideUp 0.3s ease;';
            toast.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                ${message}
            `;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 4000);
        }
        
        // AJAX helper
        function ajaxRequest(url, data, callback, method = 'POST') {
            $.ajax({
                url: url,
                type: method,
                data: data,
                dataType: 'json',
                success: function(response) {
                    callback(response);
                },
                error: function(xhr) {
                    let message = 'An error occurred. Please try again.';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        message = xhr.responseJSON.error;
                    }
                    showToast(message, 'error');
                }
            });
        }
        
        // Update balance display
        function updateBalance(real, demo) {
            if (real !== undefined) {
                document.getElementById('realBalance').textContent = formatCurrency(real);
            }
            if (demo !== undefined) {
                document.getElementById('demoBalance').textContent = formatCurrency(demo);
            }
        }
        
        // Fetch updated balance
        function refreshBalance() {
            fetch(API_URL + '/user/balance.php')
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        updateBalance(data.balance, data.demo_balance);
                    }
                });
        }
        
        // Live Chat Functions
        let chatOpen = false;
        let chatId = null;
        let lastMessageId = 0;
        let chatPollInterval = null;

        function openLiveChat() {
            if (document.getElementById('liveChatWidget')) {
                document.getElementById('liveChatWidget').classList.add('active');
                chatOpen = true;
                scrollToBottom();
                return;
            }
            
            const widget = document.createElement('div');
            widget.id = 'liveChatWidget';
            widget.className = 'live-chat-widget active';
            widget.innerHTML = `
                <div class="chat-header">
                    <div class="chat-header-info">
                        <div class="chat-avatar"><i class="fas fa-headset"></i></div>
                        <div><div class="chat-title">Live Support</div><div class="chat-status">Online</div></div>
                    </div>
                    <button class="chat-close" onclick="closeLiveChat()"><i class="fas fa-times"></i></button>
                </div>
                <div class="chat-messages" id="chatMessages">
                    <div class="chat-loading"><i class="fas fa-spinner fa-spin"></i> Connecting...</div>
                </div>
                <div class="chat-input-area">
                    <input type="text" id="chatInput" placeholder="Type your message..." onkeypress="if(event.key==='Enter')sendChatMessage()">
                    <button onclick="sendChatMessage()"><i class="fas fa-paper-plane"></i></button>
                </div>
            `;
            document.body.appendChild(widget);
            chatOpen = true;
            
            // Initialize chat
            initChat();
        }
        
        function closeLiveChat() {
            document.getElementById('liveChatWidget')?.classList.remove('active');
            chatOpen = false;
        }
        
        function initChat() {
            fetch('live-chat.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=init'
            })
            .then(r => r.json())
            .then(d => {
                if (d.success) {
                    chatId = d.chat_id;
                    const container = document.getElementById('chatMessages');
                    container.innerHTML = '';
                    
                    if (d.messages && d.messages.length > 0) {
                        d.messages.forEach(msg => appendMessage(msg));
                        lastMessageId = d.messages[d.messages.length - 1].id;
                    } else {
                        container.innerHTML = `
                            <div class="chat-message bot">
                                <div class="message-content">Hello! 👋 How can I help you today?</div>
                                <div class="message-time">Just now</div>
                            </div>
                        `;
                    }
                    scrollToBottom();
                    startPolling();
                }
            });
        }
        
        function appendMessage(msg) {
            const container = document.getElementById('chatMessages');
            const isUser = msg.is_admin == 0; // Note: is_admin is 0 for user, 1 for admin
            const type = isUser ? 'user' : 'bot';
            const time = new Date(msg.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
            
            const div = document.createElement('div');
            div.className = `chat-message ${type}`;
            div.innerHTML = `<div class="message-content">${msg.message}</div><div class="message-time">${time}</div>`;
            container.appendChild(div);
        }
        
        function scrollToBottom() {
            const container = document.getElementById('chatMessages');
            if(container) container.scrollTop = container.scrollHeight;
        }
        
        function sendChatMessage() {
            const input = document.getElementById('chatInput');
            const msg = input.value.trim();
            if (!msg || !chatId) return;
            
            // Optimistic update
            const container = document.getElementById('chatMessages');
            const time = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
            container.innerHTML += `<div class="chat-message user"><div class="message-content">${msg}</div><div class="message-time">${time}</div></div>`;
            scrollToBottom();
            input.value = '';
            
            fetch('live-chat.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `action=send_message&chat_id=${chatId}&message=${encodeURIComponent(msg)}`
            })
            .then(r => r.json())
            .then(d => {
                if (!d.success) {
                    showToast('Failed to send message', 'error');
                }
            });
        }
        
        function startPolling() {
            if (chatPollInterval) clearInterval(chatPollInterval);
            chatPollInterval = setInterval(() => {
                if (!chatOpen || !chatId) return;
                
                fetch('live-chat.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: `action=get_messages&chat_id=${chatId}&last_id=${lastMessageId}`
                })
                .then(r => r.json())
                .then(d => {
                    if (d.success && d.messages && d.messages.length > 0) {
                        d.messages.forEach(msg => {
                            if (msg.is_admin == 1) { // Only append admin messages as user messages are already shown
                                appendMessage(msg);
                            } else {
                                // Update last ID even for user messages to avoid re-fetching
                            }
                            lastMessageId = Math.max(lastMessageId, msg.id);
                        });
                        scrollToBottom();
                    }
                });
            }, 3000);
        }

        // Global Fullscreen Logic
        document.addEventListener("DOMContentLoaded", function () {
            document.querySelectorAll('.btn-full-display').forEach(function(btn) {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    // If not on trade.php, redirect there with fullscreen flag
                    if (!window.location.pathname.includes('trade.php')) {
                        window.location.href = 'trade.php?fullscreen=1';
                        return;
                    }
                    
                    if (!document.fullscreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
                        var docElm = document.documentElement;
                        if (docElm.requestFullscreen) {
                            docElm.requestFullscreen();
                        } else if (docElm.webkitRequestFullscreen) {
                            docElm.webkitRequestFullscreen();
                        } else if (docElm.msRequestFullscreen) {
                            docElm.msRequestFullscreen();
                        }
                    } else {
                        if (document.exitFullscreen) {
                            document.exitFullscreen();
                        } else if (document.webkitExitFullscreen) {
                            document.webkitExitFullscreen();
                        } else if (document.msExitFullscreen) {
                            document.msExitFullscreen();
                        }
                    }
                });
            });
        });
    </script>
    
    <!-- Live Chat Widget Styles -->
    <style>
        .live-chat-widget{position:fixed;bottom:20px;right:20px;width:350px;height:450px;background:var(--bg-card);border-radius:16px;box-shadow:0 10px 40px rgba(0,0,0,0.3);display:none;flex-direction:column;z-index:9999;overflow:hidden;border:1px solid var(--border-color)}
        .live-chat-widget.active{display:flex}
        .chat-header{display:flex;align-items:center;justify-content:space-between;padding:1rem;background:var(--accent-green);color:#000}
        .chat-header-info{display:flex;align-items:center;gap:0.75rem}
        .chat-avatar{width:40px;height:40px;border-radius:50%;background:#fff;display:flex;align-items:center;justify-content:center;font-size:1.2rem;color:var(--accent-green)}
        .chat-title{font-weight:600}
        .chat-status{font-size:0.75rem;opacity:0.8}
        .chat-close{background:none;border:none;color:#000;font-size:1.2rem;cursor:pointer}
        .chat-messages{flex:1;padding:1rem;overflow-y:auto}
        .chat-message{margin-bottom:1rem;display:flex;flex-direction:column}
        .chat-message.user{align-items:flex-end}
        .chat-message.bot{align-items:flex-start}
        .message-content{max-width:80%;padding:0.75rem 1rem;border-radius:12px;font-size:0.9rem}
        .chat-message.user .message-content{background:var(--accent-green);color:#000;border-bottom-right-radius:4px}
        .chat-message.bot .message-content{background:var(--bg-tertiary);border-bottom-left-radius:4px}
        .message-time{font-size:0.7rem;color:var(--text-muted);margin-top:0.25rem}
        .chat-input-area{display:flex;padding:1rem;border-top:1px solid var(--border-color);gap:0.5rem}
        .chat-input-area input{flex:1;padding:0.75rem;border-radius:8px;border:1px solid var(--border-color);background:var(--bg-primary);color:var(--text-primary);outline:none}
        .chat-input-area button{width:40px;height:40px;border-radius:8px;border:none;background:var(--accent-green);color:#000;cursor:pointer}
        .live-chat-btn{position:fixed;bottom:20px;right:20px;width:60px;height:60px;border-radius:50%;background:var(--accent-green);color:#000;border:none;font-size:1.5rem;cursor:pointer;box-shadow:0 4px 20px rgba(0,208,156,0.4);z-index:9998}
        @media(max-width:768px){.live-chat-widget{width:100%;height:100%;bottom:0;right:0;border-radius:0}}
    </style>
    
    <!-- Live Chat Toggle Button -->
    <button class="live-chat-btn" onclick="openLiveChat()" title="Live Chat">
        <i class="fas fa-comments"></i>
    </button>
    
    <?php if (isset($extraJs)) echo $extraJs; ?>
</body>
</html>
