<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NC1709 Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/11.1.1/marked.min.js"></script>
    <style>
        :root {
            --bg-primary: #0d1117;
            --bg-secondary: #161b22;
            --bg-tertiary: #21262d;
            --border-color: #30363d;
            --text-primary: #e6edf3;
            --text-secondary: #8b949e;
            --accent: #58a6ff;
            --accent-hover: #79b8ff;
            --success: #3fb950;
            --warning: #d29922;
            --error: #f85149;
            --sidebar-width: 260px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            line-height: 1.5;
        }

        /* Layout */
        .app {
            display: flex;
            height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: var(--sidebar-width);
            background: var(--bg-secondary);
            border-right: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
        }

        .sidebar-header {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .sidebar-header h1 {
            font-size: 20px;
            font-weight: 600;
            color: var(--accent);
        }

        .sidebar-header .version {
            font-size: 12px;
            color: var(--text-secondary);
        }

        .nav {
            flex: 1;
            padding: 8px;
            overflow-y: auto;
        }

        .nav-item {
            display: flex;
            align-items: center;
            padding: 10px 12px;
            border-radius: 6px;
            cursor: pointer;
            color: var(--text-secondary);
            transition: all 0.15s ease;
            margin-bottom: 2px;
        }

        .nav-item:hover {
            background: var(--bg-tertiary);
            color: var(--text-primary);
        }

        .nav-item.active {
            background: var(--bg-tertiary);
            color: var(--text-primary);
        }

        .nav-item svg {
            width: 16px;
            height: 16px;
            margin-right: 10px;
        }

        .nav-section {
            padding: 8px 12px 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            color: var(--text-secondary);
            margin-top: 16px;
        }

        /* Main Content */
        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            padding: 16px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .content {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
        }

        /* Chat Panel */
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }

        .message {
            margin-bottom: 16px;
            max-width: 85%;
        }

        .message.user {
            margin-left: auto;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 12px;
            background: var(--bg-tertiary);
        }

        .message.user .message-content {
            background: var(--accent);
            color: white;
        }

        .message-content pre {
            margin: 8px 0;
            padding: 12px;
            background: var(--bg-primary);
            border-radius: 6px;
            overflow-x: auto;
        }

        .message-content code {
            font-family: 'SF Mono', 'Fira Code', monospace;
            font-size: 13px;
        }

        .message-content p {
            margin-bottom: 8px;
        }

        .message-content p:last-child {
            margin-bottom: 0;
        }

        .chat-input-container {
            padding: 16px;
            border-top: 1px solid var(--border-color);
        }

        .chat-input-wrapper {
            display: flex;
            gap: 12px;
        }

        .chat-input {
            flex: 1;
            padding: 12px 16px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 14px;
            resize: none;
        }

        .chat-input:focus {
            outline: none;
            border-color: var(--accent);
        }

        .send-btn {
            padding: 12px 24px;
            background: var(--accent);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: background 0.15s ease;
        }

        .send-btn:hover {
            background: var(--accent-hover);
        }

        .send-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Cards */
        .card {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-bottom: 16px;
        }

        .card-header {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
        }

        .card-body {
            padding: 16px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 20px;
        }

        .stat-value {
            font-size: 32px;
            font-weight: 700;
            color: var(--accent);
        }

        .stat-label {
            font-size: 14px;
            color: var(--text-secondary);
            margin-top: 4px;
        }

        /* Tables */
        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th,
        .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .table th {
            font-weight: 600;
            color: var(--text-secondary);
            font-size: 12px;
            text-transform: uppercase;
        }

        /* Buttons */
        .btn {
            padding: 8px 16px;
            border-radius: 6px;
            border: 1px solid var(--border-color);
            background: var(--bg-tertiary);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 14px;
            transition: all 0.15s ease;
        }

        .btn:hover {
            background: var(--bg-secondary);
            border-color: var(--accent);
        }

        .btn-primary {
            background: var(--accent);
            border-color: var(--accent);
            color: white;
        }

        .btn-primary:hover {
            background: var(--accent-hover);
        }

        /* Status badges */
        .badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-success {
            background: rgba(63, 185, 80, 0.2);
            color: var(--success);
        }

        .badge-warning {
            background: rgba(210, 153, 34, 0.2);
            color: var(--warning);
        }

        .badge-error {
            background: rgba(248, 81, 73, 0.2);
            color: var(--error);
        }

        /* Search */
        .search-container {
            margin-bottom: 24px;
        }

        .search-input {
            width: 100%;
            padding: 12px 16px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 14px;
        }

        .search-input:focus {
            outline: none;
            border-color: var(--accent);
        }

        .search-results {
            margin-top: 16px;
        }

        .search-result {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-bottom: 12px;
            overflow: hidden;
        }

        .search-result-header {
            padding: 12px 16px;
            background: var(--bg-tertiary);
            font-size: 14px;
            display: flex;
            justify-content: space-between;
        }

        .search-result-code {
            padding: 12px 16px;
            overflow-x: auto;
        }

        .search-result-code pre {
            margin: 0;
        }

        /* Loading */
        .loading {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
            color: var(--text-secondary);
        }

        .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid var(--border-color);
            border-top-color: var(--accent);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 12px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Hidden panels */
        .panel {
            display: none;
        }

        .panel.active {
            display: block;
        }

        /* Sessions list */
        .session-item {
            padding: 12px 16px;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            transition: background 0.15s ease;
        }

        .session-item:hover {
            background: var(--bg-tertiary);
        }

        .session-item-name {
            font-weight: 500;
        }

        .session-item-meta {
            font-size: 12px;
            color: var(--text-secondary);
            margin-top: 4px;
        }

        /* Plugin/Tool lists */
        .tool-item {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .tool-item:last-child {
            border-bottom: none;
        }

        .tool-name {
            font-weight: 600;
            margin-bottom: 4px;
        }

        .tool-description {
            font-size: 14px;
            color: var(--text-secondary);
        }

        .tool-params {
            margin-top: 8px;
            font-size: 12px;
            color: var(--text-secondary);
        }

        /* Toast notifications */
        .toast-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }

        .toast {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 20px;
            margin-top: 8px;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</head>
<body>
    <div class="app">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <h1>NC1709</h1>
                <span class="version">v1.0.0 - Local AI Assistant</span>
            </div>
            <nav class="nav">
                <div class="nav-item active" data-panel="chat">
                    <svg viewBox="0 0 16 16" fill="currentColor"><path d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zm.5 4.5a.5.5 0 00-1 0v4a.5.5 0 00.5.5h2.5a.5.5 0 000-1H8.5v-3.5z"/></svg>
                    Chat
                </div>

                <div class="nav-section">Memory</div>
                <div class="nav-item" data-panel="sessions">
                    <svg viewBox="0 0 16 16" fill="currentColor"><path d="M0 1.75A.75.75 0 01.75 1h4.253a.75.75 0 01.592.288l1.67 2.168H14.25a.75.75 0 01.75.75v8.044a.75.75 0 01-.75.75H.75a.75.75 0 01-.75-.75V1.75z"/></svg>
                    Sessions
                </div>
                <div class="nav-item" data-panel="search">
                    <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.5 7a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0zm-.82 4.74a6 6 0 111.06-1.06l2.28 2.28a.75.75 0 11-1.06 1.06l-2.28-2.28z"/></svg>
                    Search Code
                </div>

                <div class="nav-section">Tools</div>
                <div class="nav-item" data-panel="plugins">
                    <svg viewBox="0 0 16 16" fill="currentColor"><path d="M2 3.75A.75.75 0 012.75 3h10.5a.75.75 0 010 1.5H2.75A.75.75 0 012 3.75zm0 4A.75.75 0 012.75 7h10.5a.75.75 0 010 1.5H2.75A.75.75 0 012 7.75zm0 4a.75.75 0 01.75-.75h10.5a.75.75 0 010 1.5H2.75a.75.75 0 01-.75-.75z"/></svg>
                    Plugins
                </div>
                <div class="nav-item" data-panel="mcp">
                    <svg viewBox="0 0 16 16" fill="currentColor"><path d="M8 0a8 8 0 100 16A8 8 0 008 0zm3.78 5.22a.75.75 0 010 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-2-2a.75.75 0 011.06-1.06L6.75 9.19l3.97-3.97a.75.75 0 011.06 0z"/></svg>
                    MCP Tools
                </div>

                <div class="nav-section">System</div>
                <div class="nav-item" data-panel="config">
                    <svg viewBox="0 0 16 16" fill="currentColor"><path d="M8 0a8.2 8.2 0 01.701.031C10.042.11 10.989.39 11.5 1.5c.4.865.464 1.92.32 2.984l.15.022c.732.1 1.332.48 1.78 1.084.447.604.67 1.39.564 2.16-.106.77-.513 1.47-1.128 2-.61.53-1.406.845-2.266.96l-.003.053a3.49 3.49 0 01-.064.498c-.164.775-.576 1.454-1.238 1.914-.66.46-1.52.629-2.315.48-.79-.15-1.513-.61-1.972-1.27a3.24 3.24 0 01-.52-1.667l-.026-.003c-.76-.11-1.456-.5-1.97-1.084a3.26 3.26 0 01-.768-2.16c.045-.77.37-1.472.928-2.005.557-.533 1.296-.852 2.101-.968l.068-.011c-.034-.355-.024-.71.03-1.064.09-.59.303-1.15.633-1.64.33-.49.77-.88 1.28-1.15A3.18 3.18 0 018 0z"/></svg>
                    Settings
                </div>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="main">
            <!-- Chat Panel -->
            <div id="panel-chat" class="panel active">
                <div class="header">
                    <h2>Chat</h2>
                    <button class="btn" onclick="clearChat()">Clear Chat</button>
                </div>
                <div class="content chat-container">
                    <div class="chat-messages" id="chat-messages">
                        <div class="message">
                            <div class="message-content">
                                <p>Welcome to NC1709! I'm your local AI developer assistant.</p>
                                <p>Ask me to help with code, search your project, manage git, docker, and more.</p>
                            </div>
                        </div>
                    </div>
                    <div class="chat-input-container">
                        <div class="chat-input-wrapper">
                            <textarea
                                class="chat-input"
                                id="chat-input"
                                placeholder="Ask me anything..."
                                rows="1"
                                onkeydown="handleChatKeydown(event)"
                            ></textarea>
                            <button class="send-btn" id="send-btn" onclick="sendMessage()">Send</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sessions Panel -->
            <div id="panel-sessions" class="panel">
                <div class="header">
                    <h2>Sessions</h2>
                    <button class="btn btn-primary" onclick="createSession()">New Session</button>
                </div>
                <div class="content">
                    <div id="sessions-list" class="card">
                        <div class="loading"><div class="spinner"></div> Loading sessions...</div>
                    </div>
                </div>
            </div>

            <!-- Search Panel -->
            <div id="panel-search" class="panel">
                <div class="header">
                    <h2>Semantic Code Search</h2>
                    <button class="btn" onclick="indexProject()">Re-index Project</button>
                </div>
                <div class="content">
                    <div id="index-status" class="stats-grid">
                        <!-- Index stats loaded here -->
                    </div>
                    <div class="search-container">
                        <input
                            type="text"
                            class="search-input"
                            id="search-input"
                            placeholder="Search your code semantically... (e.g., 'authentication logic')"
                            onkeydown="if(event.key==='Enter')searchCode()"
                        >
                    </div>
                    <div id="search-results" class="search-results">
                        <!-- Results loaded here -->
                    </div>
                </div>
            </div>

            <!-- Plugins Panel -->
            <div id="panel-plugins" class="panel">
                <div class="header">
                    <h2>Plugins</h2>
                </div>
                <div class="content">
                    <div id="plugins-list">
                        <div class="loading"><div class="spinner"></div> Loading plugins...</div>
                    </div>
                </div>
            </div>

            <!-- MCP Panel -->
            <div id="panel-mcp" class="panel">
                <div class="header">
                    <h2>MCP Tools</h2>
                </div>
                <div class="content">
                    <div id="mcp-status" class="stats-grid">
                        <!-- MCP stats loaded here -->
                    </div>
                    <div id="mcp-tools" class="card">
                        <div class="card-header">Available Tools</div>
                        <div class="card-body" id="mcp-tools-list">
                            <div class="loading"><div class="spinner"></div> Loading tools...</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Config Panel -->
            <div id="panel-config" class="panel">
                <div class="header">
                    <h2>Settings</h2>
                </div>
                <div class="content">
                    <div class="stats-grid" id="system-status">
                        <!-- Status loaded here -->
                    </div>
                    <div class="card">
                        <div class="card-header">Configuration</div>
                        <div class="card-body">
                            <pre id="config-display" style="background: var(--bg-primary); padding: 16px; border-radius: 6px; overflow-x: auto;"></pre>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <div class="toast-container" id="toast-container"></div>

    <script>
        // Configure marked
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            },
            breaks: true
        });

        // Navigation
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', () => {
                const panel = item.dataset.panel;
                if (panel) {
                    // Update nav
                    document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
                    item.classList.add('active');

                    // Update panels
                    document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
                    document.getElementById(`panel-${panel}`).classList.add('active');

                    // Load data for panel
                    loadPanelData(panel);
                }
            });
        });

        // Load panel data
        function loadPanelData(panel) {
            switch(panel) {
                case 'sessions':
                    loadSessions();
                    break;
                case 'search':
                    loadIndexStatus();
                    break;
                case 'plugins':
                    loadPlugins();
                    break;
                case 'mcp':
                    loadMCPStatus();
                    loadMCPTools();
                    break;
                case 'config':
                    loadConfig();
                    loadStatus();
                    break;
            }
        }

        // Toast notifications
        function showToast(message, type = 'info') {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = message;
            container.appendChild(toast);

            setTimeout(() => toast.remove(), 3000);
        }

        // Chat functions
        function addMessage(role, content) {
            const messages = document.getElementById('chat-messages');
            const div = document.createElement('div');
            div.className = `message ${role}`;

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';

            if (role === 'assistant') {
                contentDiv.innerHTML = marked.parse(content);
                contentDiv.querySelectorAll('pre code').forEach(block => {
                    hljs.highlightElement(block);
                });
            } else {
                contentDiv.textContent = content;
            }

            div.appendChild(contentDiv);
            messages.appendChild(div);
            messages.scrollTop = messages.scrollHeight;
        }

        async function sendMessage() {
            const input = document.getElementById('chat-input');
            const btn = document.getElementById('send-btn');
            const message = input.value.trim();

            if (!message) return;

            // Add user message
            addMessage('user', message);
            input.value = '';
            btn.disabled = true;

            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });

                const data = await response.json();

                if (response.ok) {
                    addMessage('assistant', data.response);
                } else {
                    addMessage('assistant', `Error: ${data.detail}`);
                }
            } catch (e) {
                addMessage('assistant', `Error: ${e.message}`);
            } finally {
                btn.disabled = false;
                input.focus();
            }
        }

        function handleChatKeydown(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        }

        function clearChat() {
            const messages = document.getElementById('chat-messages');
            messages.innerHTML = `
                <div class="message">
                    <div class="message-content">
                        <p>Chat cleared. How can I help you?</p>
                    </div>
                </div>
            `;
        }

        // Sessions
        async function loadSessions() {
            const container = document.getElementById('sessions-list');

            try {
                const response = await fetch('/api/sessions');
                const data = await response.json();

                if (data.sessions.length === 0) {
                    container.innerHTML = '<div class="card-body">No sessions yet. Start chatting to create one!</div>';
                    return;
                }

                container.innerHTML = data.sessions.map(s => `
                    <div class="session-item" onclick="loadSession('${s.id}')">
                        <div class="session-item-name">${s.name || s.id}</div>
                        <div class="session-item-meta">
                            ${s.message_count || 0} messages • ${s.updated_at ? s.updated_at.slice(0, 16) : 'N/A'}
                        </div>
                    </div>
                `).join('');
            } catch (e) {
                container.innerHTML = `<div class="card-body">Error loading sessions: ${e.message}</div>`;
            }
        }

        async function loadSession(id) {
            try {
                const response = await fetch(`/api/sessions/${id}`);
                const data = await response.json();

                // Switch to chat panel and load messages
                document.querySelector('[data-panel="chat"]').click();

                const messages = document.getElementById('chat-messages');
                messages.innerHTML = '';

                data.messages.forEach(m => {
                    addMessage(m.role, m.content);
                });

                showToast(`Loaded session: ${data.name || id}`);
            } catch (e) {
                showToast(`Error loading session: ${e.message}`, 'error');
            }
        }

        async function createSession() {
            try {
                const response = await fetch('/api/sessions', { method: 'POST' });
                const data = await response.json();
                showToast(`Created session: ${data.id}`);
                loadSessions();
            } catch (e) {
                showToast(`Error: ${e.message}`, 'error');
            }
        }

        // Search
        async function loadIndexStatus() {
            const container = document.getElementById('index-status');

            try {
                const response = await fetch('/api/index/status');
                const data = await response.json();

                container.innerHTML = `
                    <div class="stat-card">
                        <div class="stat-value">${data.total_files || 0}</div>
                        <div class="stat-label">Files Indexed</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value">${data.total_chunks || 0}</div>
                        <div class="stat-label">Code Chunks</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value">${Object.keys(data.languages || {}).length}</div>
                        <div class="stat-label">Languages</div>
                    </div>
                `;
            } catch (e) {
                container.innerHTML = `<div class="stat-card">Error loading index status</div>`;
            }
        }

        async function searchCode() {
            const input = document.getElementById('search-input');
            const results = document.getElementById('search-results');
            const query = input.value.trim();

            if (!query) return;

            results.innerHTML = '<div class="loading"><div class="spinner"></div> Searching...</div>';

            try {
                const response = await fetch('/api/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ query, n_results: 5 })
                });

                const data = await response.json();

                if (data.results.length === 0) {
                    results.innerHTML = '<p>No results found.</p>';
                    return;
                }

                results.innerHTML = data.results.map(r => `
                    <div class="search-result">
                        <div class="search-result-header">
                            <span>${r.location}</span>
                            <span class="badge badge-success">${(r.similarity * 100).toFixed(1)}% match</span>
                        </div>
                        <div class="search-result-code">
                            <pre><code class="language-${r.language || 'plaintext'}">${escapeHtml(r.content)}</code></pre>
                        </div>
                    </div>
                `).join('');

                // Highlight code
                results.querySelectorAll('pre code').forEach(block => {
                    hljs.highlightElement(block);
                });
            } catch (e) {
                results.innerHTML = `<p>Error: ${e.message}</p>`;
            }
        }

        async function indexProject() {
            showToast('Indexing project...');

            try {
                const response = await fetch('/api/index', { method: 'POST' });
                const data = await response.json();

                showToast(`Indexed ${data.files_indexed} files, ${data.chunks_created} chunks`);
                loadIndexStatus();
            } catch (e) {
                showToast(`Error: ${e.message}`, 'error');
            }
        }

        // Plugins
        async function loadPlugins() {
            const container = document.getElementById('plugins-list');

            try {
                const response = await fetch('/api/plugins');
                const data = await response.json();

                if (data.plugins.length === 0) {
                    container.innerHTML = '<p>No plugins available.</p>';
                    return;
                }

                container.innerHTML = data.plugins.map(p => `
                    <div class="card" style="margin-bottom: 16px;">
                        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
                            <span>${p.name} <span style="color: var(--text-secondary);">v${p.version}</span></span>
                            <span class="badge ${p.status === 'active' ? 'badge-success' : 'badge-warning'}">${p.status}</span>
                        </div>
                        <div class="card-body">
                            <p style="color: var(--text-secondary); margin-bottom: 12px;">
                                ${p.builtin ? 'Built-in plugin' : 'Custom plugin'}
                            </p>
                            <div>
                                <strong>Actions:</strong>
                                ${p.actions.map(a => `<button class="btn" style="margin: 4px;" onclick="executePlugin('${p.name}', '${a}')">${a}</button>`).join('')}
                            </div>
                        </div>
                    </div>
                `).join('');
            } catch (e) {
                container.innerHTML = `<p>Error: ${e.message}</p>`;
            }
        }

        async function executePlugin(plugin, action) {
            try {
                const response = await fetch('/api/plugins/execute', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ plugin, action })
                });

                const data = await response.json();

                if (data.success) {
                    showToast(data.message);
                    // Show result in chat
                    document.querySelector('[data-panel="chat"]').click();
                    addMessage('assistant', `**${plugin}:${action}**\n\n${data.message}\n\n${typeof data.data === 'string' ? data.data : JSON.stringify(data.data, null, 2)}`);
                } else {
                    showToast(`Error: ${data.error}`, 'error');
                }
            } catch (e) {
                showToast(`Error: ${e.message}`, 'error');
            }
        }

        // MCP
        async function loadMCPStatus() {
            const container = document.getElementById('mcp-status');

            try {
                const response = await fetch('/api/mcp/status');
                const data = await response.json();

                if (!data.available) {
                    container.innerHTML = '<div class="stat-card">MCP not available</div>';
                    return;
                }

                container.innerHTML = `
                    <div class="stat-card">
                        <div class="stat-value">${data.server.tools}</div>
                        <div class="stat-label">Local Tools</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value">${data.client.connected_servers}</div>
                        <div class="stat-label">Connected Servers</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value">${data.server.running ? 'Yes' : 'No'}</div>
                        <div class="stat-label">Server Running</div>
                    </div>
                `;
            } catch (e) {
                container.innerHTML = `<div class="stat-card">Error loading MCP status</div>`;
            }
        }

        async function loadMCPTools() {
            const container = document.getElementById('mcp-tools-list');

            try {
                const response = await fetch('/api/mcp/tools');
                const data = await response.json();

                const tools = [...data.local, ...data.remote];

                if (tools.length === 0) {
                    container.innerHTML = '<p>No tools available.</p>';
                    return;
                }

                container.innerHTML = tools.map(t => `
                    <div class="tool-item">
                        <div class="tool-name">${t.name}</div>
                        <div class="tool-description">${t.description}</div>
                        ${t.parameters ? `<div class="tool-params">Parameters: ${t.parameters.map(p => p.name).join(', ')}</div>` : ''}
                    </div>
                `).join('');
            } catch (e) {
                container.innerHTML = `<p>Error: ${e.message}</p>`;
            }
        }

        // Config
        async function loadConfig() {
            const display = document.getElementById('config-display');

            try {
                const response = await fetch('/api/config');
                const data = await response.json();
                display.textContent = JSON.stringify(data.config, null, 2);
            } catch (e) {
                display.textContent = `Error: ${e.message}`;
            }
        }

        async function loadStatus() {
            const container = document.getElementById('system-status');

            try {
                const response = await fetch('/api/status');
                const data = await response.json();

                container.innerHTML = `
                    <div class="stat-card">
                        <div class="stat-value" style="font-size: 20px;">${data.status === 'ok' ? '✅' : '❌'}</div>
                        <div class="stat-label">System Status</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" style="font-size: 16px;">${data.version}</div>
                        <div class="stat-label">Version</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value" style="font-size: 14px; word-break: break-all;">${data.project.slice(-30)}</div>
                        <div class="stat-label">Project</div>
                    </div>
                `;
            } catch (e) {
                container.innerHTML = `<div class="stat-card">Error loading status</div>`;
            }
        }

        // Utilities
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Initial load
        loadStatus();
    </script>
</body>
</html>
