"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AxionAIViewProvider = void 0;
const vscode = __importStar(require("vscode"));
const AIService_1 = require("../services/AIService");
const ConversationManager_1 = require("../services/ConversationManager");
const AIModels_1 = require("../models/AIModels");
class AxionAIViewProvider {
    extensionUri;
    context;
    fileManager;
    changeTracker;
    static viewType = 'axion-ai.chatView';
    _view;
    aiService;
    conversationManager;
    currentModel;
    currentMode = 'agent';
    isGenerating = false;
    abortController;
    constructor(extensionUri, context, fileManager, changeTracker) {
        this.extensionUri = extensionUri;
        this.context = context;
        this.fileManager = fileManager;
        this.changeTracker = changeTracker;
        this.aiService = new AIService_1.AIService();
        this.conversationManager = new ConversationManager_1.ConversationManager(context);
        this.currentModel = (0, AIModels_1.getModelById)('claude-sonnet-4') || AIModels_1.AI_MODELS[0];
    }
    resolveWebviewView(webviewView, context, _token) {
        this._view = webviewView;
        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this.extensionUri]
        };
        webviewView.webview.html = this.getHtmlContent(webviewView.webview, this.extensionUri);
        webviewView.webview.onDidReceiveMessage(async (message) => {
            await this.handleMessage(message);
        });
        this.sendInitialState();
    }
    async sendInitialState() {
        if (!this._view)
            return;
        // Get or create conversation
        let conversation = this.conversationManager.getCurrentConversation();
        if (!conversation) {
            conversation = this.conversationManager.createConversation(this.currentMode, this.currentModel.id);
        }
        this._view.webview.postMessage({
            type: 'init',
            payload: {
                models: AIModels_1.AI_MODELS.map(m => ({
                    id: m.id,
                    name: m.name,
                    provider: m.provider,
                    supportsVision: m.supportsVision,
                    supportsThinking: m.supportsThinking
                })),
                providers: AIModels_1.AI_PROVIDERS,
                currentModel: this.currentModel.id,
                currentMode: this.currentMode,
                apiKeys: this.getStoredApiKeys(),
                conversations: this.conversationManager.getAllConversations().map(c => ({
                    id: c.id,
                    title: c.title,
                    updatedAt: c.updatedAt.toISOString(),
                    messageCount: c.messages.length
                })),
                currentConversationId: conversation.id,
                messages: conversation.messages
            }
        });
        // Send workspace files
        const files = await this.fileManager.getWorkspaceFiles();
        this._view.webview.postMessage({
            type: 'files',
            payload: this.buildFileTree(files)
        });
    }
    buildFileTree(files) {
        const tree = {};
        for (const file of files) {
            const parts = file.relativePath.split(/[\/\\]/);
            let current = tree;
            for (let i = 0; i < parts.length; i++) {
                const part = parts[i];
                if (i === parts.length - 1) {
                    // File
                    if (!current._files)
                        current._files = [];
                    current._files.push({
                        name: part,
                        path: file.path,
                        language: file.language
                    });
                }
                else {
                    // Directory
                    if (!current[part])
                        current[part] = {};
                    current = current[part];
                }
            }
        }
        return tree;
    }
    getStoredApiKeys() {
        const keys = {};
        for (const provider of AIModels_1.AI_PROVIDERS) {
            keys[provider.id] = this.aiService.hasApiKey(provider.id);
        }
        return keys;
    }
    async handleMessage(message) {
        switch (message.type) {
            case 'sendMessage':
                await this.handleChatMessage(message.payload.content);
                break;
            case 'stopGeneration':
                this.stopGeneration();
                break;
            case 'setModel':
                const model = (0, AIModels_1.getModelById)(message.payload.modelId);
                if (model) {
                    this.currentModel = model;
                    this.conversationManager.updateConversationModel(model.id);
                }
                break;
            case 'setMode':
                this.currentMode = message.payload.mode;
                this.conversationManager.updateConversationMode(this.currentMode);
                break;
            case 'setApiKey':
                this.aiService.setApiKey(message.payload.provider, message.payload.key);
                await this.saveApiKey(message.payload.provider, message.payload.key);
                this._view?.webview.postMessage({
                    type: 'apiKeySet',
                    payload: { provider: message.payload.provider, success: true }
                });
                break;
            case 'applyChange':
                await this.applyFileChange(message.payload.changeId);
                break;
            case 'revertChange':
                await this.revertFileChange(message.payload.changeId);
                break;
            case 'readFile':
                const content = await this.fileManager.readFile(message.payload.path);
                this._view?.webview.postMessage({
                    type: 'fileContent',
                    payload: content
                });
                break;
            case 'openFile':
                const uri = vscode.Uri.file(message.payload.path);
                const doc = await vscode.workspace.openTextDocument(uri);
                await vscode.window.showTextDocument(doc);
                break;
            case 'newChat':
                this.newChat();
                break;
            case 'loadConversation':
                this.loadConversation(message.payload.conversationId);
                break;
            case 'deleteConversation':
                this.deleteConversation(message.payload.conversationId);
                break;
            case 'getFiles':
                const files = await this.fileManager.getWorkspaceFiles();
                this._view?.webview.postMessage({
                    type: 'files',
                    payload: this.buildFileTree(files)
                });
                break;
            case 'copyToClipboard':
                await vscode.env.clipboard.writeText(message.payload.text);
                vscode.window.showInformationMessage('Copied to clipboard!');
                break;
            case 'insertAtCursor':
                const editor = vscode.window.activeTextEditor;
                if (editor) {
                    editor.edit(editBuilder => {
                        editBuilder.insert(editor.selection.active, message.payload.text);
                    });
                }
                break;
        }
    }
    stopGeneration() {
        if (this.abortController) {
            this.abortController.abort();
            this.abortController = undefined;
        }
        this.isGenerating = false;
        this._view?.webview.postMessage({ type: 'generationStopped' });
    }
    async handleChatMessage(content) {
        if (!this._view || this.isGenerating)
            return;
        // Add user message
        const userMessage = { role: 'user', content };
        this.conversationManager.addMessage(userMessage);
        this._view.webview.postMessage({
            type: 'userMessage',
            payload: { content }
        });
        // Check API key
        if (!this.aiService.hasApiKey(this.currentModel.provider)) {
            this._view.webview.postMessage({
                type: 'error',
                payload: {
                    message: `Please set your ${this.currentModel.provider} API key first. Click the settings icon to configure.`
                }
            });
            return;
        }
        // Get context
        let context = '';
        const files = await this.fileManager.getWorkspaceFiles();
        context = `Project structure:\n${files.slice(0, 50).map(f => f.relativePath).join('\n')}`;
        const activeFile = await this.fileManager.getActiveFileContent();
        if (activeFile) {
            const truncatedContent = activeFile.content.length > 10000
                ? activeFile.content.substring(0, 10000) + '\n... (truncated)'
                : activeFile.content;
            context += `\n\nCurrently open file (${activeFile.path}):\n\`\`\`${activeFile.language}\n${truncatedContent}\n\`\`\``;
        }
        // Start generation
        this.isGenerating = true;
        this.abortController = new AbortController();
        this._view.webview.postMessage({ type: 'generationStarted' });
        try {
            let fullContent = '';
            const response = await this.aiService.chat(this.currentModel, this.conversationManager.getMessages(), this.currentMode, context, (chunk, type) => {
                if (type === 'content') {
                    fullContent += chunk;
                    this._view?.webview.postMessage({
                        type: 'streamChunk',
                        payload: { chunk, fullContent }
                    });
                }
            });
            // Add assistant message
            const assistantMessage = { role: 'assistant', content: response.content };
            this.conversationManager.addMessage(assistantMessage);
            // Parse file changes if in agent mode
            let changes = [];
            if (this.currentMode === 'agent') {
                const fileChanges = this.aiService.parseFileChanges(response.content);
                for (const change of fileChanges) {
                    const existingContent = await this.fileManager.readFile(change.path);
                    const tracked = await this.changeTracker.trackChange(change.path, existingContent?.content || '', change.content, 'AI suggested change');
                    changes.push(tracked);
                }
            }
            this._view?.webview.postMessage({
                type: 'streamComplete',
                payload: {
                    content: response.content,
                    usage: response.usage,
                    changes: changes.map(c => ({
                        id: c.id,
                        filePath: c.filePath,
                        description: c.description,
                        applied: c.applied
                    }))
                }
            });
        }
        catch (error) {
            if (error.name === 'AbortError') {
                // Generation was stopped by user
                return;
            }
            const errorMessage = error instanceof Error ? error.message : 'An error occurred';
            this._view?.webview.postMessage({
                type: 'error',
                payload: { message: errorMessage }
            });
        }
        finally {
            this.isGenerating = false;
            this.abortController = undefined;
            this._view?.webview.postMessage({ type: 'generationEnded' });
        }
    }
    async applyFileChange(changeId) {
        const success = await this.changeTracker.applyChange(changeId);
        this._view?.webview.postMessage({
            type: 'changeApplied',
            payload: { changeId, success }
        });
        if (success) {
            vscode.window.showInformationMessage('✅ Change applied successfully!');
        }
    }
    async revertFileChange(changeId) {
        const success = await this.changeTracker.revertChange(changeId);
        this._view?.webview.postMessage({
            type: 'changeReverted',
            payload: { changeId, success }
        });
        if (success) {
            vscode.window.showInformationMessage('Change reverted!');
        }
    }
    async saveApiKey(provider, key) {
        const config = vscode.workspace.getConfiguration('axion-ai');
        const keyMap = {
            'anthropic': 'anthropicApiKey',
            'openai': 'openaiApiKey',
            'google': 'googleApiKey',
            'xai': 'xaiApiKey',
            'deepseek': 'deepseekApiKey',
            'mistral': 'mistralApiKey',
            'groq': 'groqApiKey',
            'huggingface': 'huggingfaceApiKey',
            'together': 'togetherApiKey',
            'perplexity': 'perplexityApiKey'
        };
        const configKey = keyMap[provider];
        if (configKey) {
            await config.update(configKey, key, vscode.ConfigurationTarget.Global);
        }
    }
    newChat() {
        const conversation = this.conversationManager.createConversation(this.currentMode, this.currentModel.id);
        this.changeTracker.endSession();
        this.changeTracker.startSession();
        this._view?.webview.postMessage({
            type: 'newChatCreated',
            payload: {
                conversationId: conversation.id,
                conversations: this.conversationManager.getAllConversations().map(c => ({
                    id: c.id,
                    title: c.title,
                    updatedAt: c.updatedAt.toISOString(),
                    messageCount: c.messages.length
                }))
            }
        });
    }
    async sendMessage(content) {
        if (!this._view) {
            await vscode.commands.executeCommand('axion-ai.chatView.focus');
        }
        await this.handleChatMessage(content);
    }
    clearHistory() {
        this.conversationManager.clearAll();
        this._view?.webview.postMessage({
            type: 'historyCleared'
        });
    }
    async exportConversation() {
        const conversation = this.conversationManager.getCurrentConversation();
        if (!conversation || conversation.messages.length === 0) {
            return null;
        }
        let markdown = `# Axion AI Conversation\n\n`;
        markdown += `**Mode:** ${conversation.mode}\n`;
        markdown += `**Model:** ${conversation.modelId}\n`;
        markdown += `**Date:** ${conversation.updatedAt.toISOString()}\n\n`;
        markdown += `---\n\n`;
        for (const msg of conversation.messages) {
            markdown += `## ${msg.role === 'user' ? 'You' : 'Axion AI'}\n\n`;
            markdown += `${msg.content}\n\n`;
            markdown += `---\n\n`;
        }
        return markdown;
    }
    async importConversation(content) {
        // Simple import - create new conversation and add messages
        const conversation = this.conversationManager.createConversation(this.currentMode, this.currentModel.id);
        // Parse and add messages from content
        // This is a simplified version - you might want more robust parsing
        this._view?.webview.postMessage({
            type: 'conversationImported',
            payload: { conversationId: conversation.id }
        });
    }
    loadConversation(conversationId) {
        if (this.conversationManager.setCurrentConversation(conversationId)) {
            const conversation = this.conversationManager.getCurrentConversation();
            if (conversation) {
                this.currentMode = conversation.mode;
                const model = (0, AIModels_1.getModelById)(conversation.modelId);
                if (model) {
                    this.currentModel = model;
                }
                this._view?.webview.postMessage({
                    type: 'conversationLoaded',
                    payload: {
                        conversationId: conversation.id,
                        messages: conversation.messages,
                        mode: conversation.mode,
                        modelId: conversation.modelId
                    }
                });
            }
        }
    }
    deleteConversation(conversationId) {
        this.conversationManager.deleteConversation(conversationId);
        this._view?.webview.postMessage({
            type: 'conversationDeleted',
            payload: {
                conversationId,
                conversations: this.conversationManager.getAllConversations().map(c => ({
                    id: c.id,
                    title: c.title,
                    updatedAt: c.updatedAt.toISOString(),
                    messageCount: c.messages.length
                }))
            }
        });
    }
    getHtmlContent(webview, extensionUri) {
        const logoUri = webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, 'media', 'logo.png'));
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Axion AI</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <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/12.0.0/marked.min.js"></script>
    <style>
        :root {
            --primary: #FFFFFF;
            --primary-dark: #E5E5E5;
            --primary-light: #F5F5F5;
            --secondary: #000000;
            --accent: #808080;
            --success: #FFFFFF;
            --warning: #CCCCCC;
            --danger: #FF4444;
            --bg-primary: #000000;
            --bg-secondary: #0A0A0A;
            --bg-tertiary: #141414;
            --bg-elevated: #1A1A1A;
            --bg-hover: #242424;
            --text-primary: #FFFFFF;
            --text-secondary: #B0B0B0;
            --text-muted: #707070;
            --border: #2A2A2A;
            --border-light: #3A3A3A;
            --glow: rgba(255, 255, 255, 0.1);
            --agent-color: #FFFFFF;
            --ask-color: #E0E0E0;
            --library-color: #C0C0C0;
        }

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

        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            height: 100vh;
            overflow: hidden;
            -webkit-font-smoothing: antialiased;
            font-weight: 400;
            letter-spacing: -0.01em;
        }

        .app {
            display: flex;
            flex-direction: column;
            height: 100vh;
            background: linear-gradient(180deg, var(--bg-primary) 0%, #0A0A0F 100%);
        }

        /* Header */
        .header {
            padding: 16px 18px;
            background: rgba(22, 22, 29, 0.95);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border);
            z-index: 100;
        }

        .header-top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo-img {
            width: 24px;
            height: 24px;
            object-fit: contain;
        }

        .logo-text {
            font-size: 15px;
            font-weight: 600;
            color: var(--text-primary);
            letter-spacing: -0.02em;
        }

        .header-actions {
            display: flex;
            gap: 6px;
        }

        .icon-btn {
            padding: 8px 14px;
            border: none;
            background: var(--bg-tertiary);
            color: var(--text-secondary);
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            font-size: 12px;
            font-weight: 500;
            border: 1px solid var(--border);
            font-family: inherit;
        }

        .icon-btn:hover {
            background: var(--bg-hover);
            color: var(--text-primary);
            border-color: var(--border-light);
        }

        /* Tab Bar */
        .tab-bar {
            display: flex;
            gap: 2px;
            background: var(--bg-tertiary);
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 10px;
        }

        .tab {
            flex: 1;
            padding: 8px 10px;
            border: none;
            background: transparent;
            color: var(--text-muted);
            font-size: 11px;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .tab:hover { color: var(--text-secondary); background: var(--bg-hover); }
        .tab.active { background: var(--bg-elevated); color: var(--text-primary); }

        /* Model Select */
        .model-row {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
        }

        .select-wrap {
            flex: 1;
            position: relative;
        }

        .select {
            width: 100%;
            padding: 11px 32px 11px 14px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            appearance: none;
            transition: all 0.2s ease;
            font-family: inherit;
        }

        .select:hover { border-color: var(--border-light); }
        .select:focus { outline: none; border-color: var(--text-primary); box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1); }

        .select-wrap::after {
            content: '▾';
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 10px;
            color: var(--text-muted);
            pointer-events: none;
        }

        /* Futuristic Mode Selector */
        .mode-selector-container {
            position: relative;
            margin-bottom: 0;
        }

        .mode-selector-label {
            font-size: 11px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }

        .mode-tabs {
            display: flex;
            gap: 6px;
            overflow-x: auto;
            padding: 6px;
            background: var(--bg-tertiary);
            border-radius: 8px;
            border: 1px solid var(--border);
            scrollbar-width: thin;
            scrollbar-color: var(--primary) transparent;
        }

        .mode-tabs::-webkit-scrollbar {
            height: 4px;
        }

        .mode-tabs::-webkit-scrollbar-track {
            background: transparent;
        }

        .mode-tabs::-webkit-scrollbar-thumb {
            background: var(--text-muted);
            border-radius: 2px;
        }

        .mode-tab {
            padding: 10px 16px;
            border: 1px solid var(--border);
            background: var(--bg-elevated);
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 500;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            white-space: nowrap;
            position: relative;
            letter-spacing: -0.01em;
        }

        .mode-tab:hover {
            color: var(--text-primary);
            background: var(--bg-hover);
            border-color: var(--border-light);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .mode-tab.active {
            color: var(--bg-primary);
            background: var(--text-primary);
            border-color: var(--text-primary);
        }

        .mode-tab.active .mode-icon {
            opacity: 1;
        }


        .mode-tab.active[data-mode="agent"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="ask"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="library"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="swarm"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="evolution"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="quantum"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="neural"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="timetravel"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="predictive"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="mindmeld"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="parallel"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="dna"] { background: var(--text-primary); color: var(--bg-primary); }
        .mode-tab.active[data-mode="collaborative"] { background: var(--text-primary); color: var(--bg-primary); }

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

        /* Sidebar */
        .sidebar {
            width: 0;
            background: var(--bg-secondary);
            border-right: 1px solid var(--border);
            overflow: hidden;
            transition: width 0.3s ease;
        }

        .sidebar.open { width: 220px; }

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

        .sidebar-title {
            font-size: 12px;
            font-weight: 600;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .sidebar-content {
            padding: 8px;
            overflow-y: auto;
            height: calc(100% - 45px);
        }

        .conversation-item {
            padding: 10px 12px;
            border-radius: 8px;
            cursor: pointer;
            margin-bottom: 4px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .conversation-item:hover { background: var(--bg-hover); }
        .conversation-item.active { background: var(--bg-elevated); border: 1px solid var(--border); }

        .conversation-title {
            font-size: 12px;
            color: var(--text-primary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
        }

        .conversation-delete {
            opacity: 0;
            padding: 4px 8px;
            background: none;
            border: 1px solid var(--border);
            color: var(--text-muted);
            cursor: pointer;
            font-size: 11px;
            font-weight: 500;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .conversation-item:hover .conversation-delete { opacity: 1; }
        .conversation-delete:hover { background: var(--danger); color: white; border-color: var(--danger); }

        /* Chat Area */
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            scroll-behavior: smooth;
        }

        .chat::-webkit-scrollbar { width: 6px; }
        .chat::-webkit-scrollbar-track { background: transparent; }
        .chat::-webkit-scrollbar-thumb { background: var(--bg-elevated); border-radius: 3px; }
        .chat::-webkit-scrollbar-thumb:hover { background: var(--bg-hover); }

        /* Messages */
        .msg {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            animation: fadeIn 0.3s ease;
        }

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

        .msg.user { flex-direction: row-reverse; }

        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            font-weight: 600;
            flex-shrink: 0;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .msg.assistant .avatar {
            background: var(--bg-elevated);
            border: 1px solid var(--border);
            color: var(--text-secondary);
        }

        .msg.user .avatar { 
            background: var(--bg-elevated);
            border: 1px solid var(--border);
            color: var(--text-secondary);
        }

        .bubble {
            max-width: 85%;
            padding: 14px 18px;
            border-radius: 12px;
            font-size: 14px;
            line-height: 1.65;
            word-wrap: break-word;
            font-weight: 400;
        }

        .msg.user .bubble {
            background: var(--bg-elevated);
            border: 1px solid var(--border);
            color: var(--text-primary);
            border-bottom-right-radius: 4px;
        }

        .msg.assistant .bubble {
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-bottom-left-radius: 4px;
        }

        /* Markdown Styles */
        .bubble h1, .bubble h2, .bubble h3, .bubble h4 {
            margin: 16px 0 8px;
            font-weight: 600;
            color: var(--text-primary);
        }

        .bubble h1 { font-size: 18px; }
        .bubble h2 { font-size: 16px; }
        .bubble h3 { font-size: 14px; }
        .bubble h4 { font-size: 13px; }

        .bubble p { margin: 8px 0; }
        .bubble ul, .bubble ol { margin: 8px 0; padding-left: 24px; }
        .bubble li { margin: 4px 0; }
        .bubble strong { color: var(--text-primary); }
        .bubble em { color: var(--text-secondary); }

        .bubble a {
            color: var(--text-primary);
            text-decoration: underline;
            text-decoration-color: var(--text-muted);
        }
        .bubble a:hover { text-decoration: underline; }

        .bubble blockquote {
            border-left: 2px solid var(--border);
            padding-left: 12px;
            margin: 12px 0;
            color: var(--text-secondary);
        }

        .bubble hr {
            border: none;
            border-top: 1px solid var(--border);
            margin: 16px 0;
        }

        /* Code Blocks */
        .bubble code {
            font-family: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;
            font-size: 12px;
            background: var(--bg-primary);
            padding: 2px 6px;
            border-radius: 4px;
            color: var(--text-secondary);
        }

        .bubble pre {
            margin: 12px 0;
            border-radius: 12px;
            overflow: hidden;
            position: relative;
            background: var(--bg-primary);
            border: 1px solid var(--border);
        }

        .bubble pre code {
            display: block;
            padding: 14px;
            overflow-x: auto;
            font-size: 12px;
            line-height: 1.6;
            background: transparent;
            color: var(--text-primary);
        }

        .code-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 12px;
            background: var(--bg-elevated);
            border-bottom: 1px solid var(--border);
        }

        .code-lang {
            font-size: 10px;
            font-weight: 600;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .code-actions { display: flex; gap: 4px; }

        .code-btn {
            padding: 5px 12px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 6px;
            color: var(--text-secondary);
            font-size: 11px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            font-family: inherit;
        }

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

        /* File Changes */
        .changes { margin-top: 12px; display: flex; flex-direction: column; gap: 8px; }

        .change-card {
            background: var(--bg-secondary);
            border: 1px solid var(--border);
            border-radius: 12px;
            overflow: hidden;
        }

        .change-header {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 12px;
            background: var(--bg-tertiary);
        }


        .change-path {
            flex: 1;
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            color: var(--text-secondary);
        }

        .change-actions { display: flex; gap: 6px; }

        .change-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .change-btn.apply {
            background: var(--bg-elevated);
            border: 1px solid var(--border);
            color: var(--text-primary);
        }
        .change-btn.apply:hover { 
            background: var(--bg-hover);
            border-color: var(--border-light);
        }

        .change-btn.revert {
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            color: var(--text-secondary);
        }
        .change-btn.revert:hover { 
            background: var(--bg-hover);
            color: var(--text-primary);
        }

        .change-btn.applied {
            background: var(--bg-elevated);
            color: var(--text-muted);
            cursor: default;
        }

        /* Typing Indicator */
        .typing { display: none; padding: 0 16px 16px; }
        .typing.visible { display: flex; align-items: center; gap: 12px; }

        .typing-dots {
            display: flex;
            gap: 5px;
            padding: 12px 16px;
            background: var(--bg-tertiary);
            border-radius: 16px;
            border: 1px solid var(--border);
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: var(--text-primary);
            border-radius: 50%;
            animation: bounce 1.4s ease-in-out infinite;
        }

        .typing-dot:nth-child(2) { animation-delay: 0.15s; }
        .typing-dot:nth-child(3) { animation-delay: 0.3s; }

        @keyframes bounce {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-8px); }
        }

        /* Empty State */
        .empty {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            padding: 40px 20px;
            text-align: center;
        }

        .empty-icon {
            font-size: 48px;
            margin-bottom: 20px;
            color: var(--text-muted);
            font-weight: 100;
            letter-spacing: 2px;
        }

        .empty h3 {
            font-size: 20px;
            font-weight: 300;
            margin-bottom: 8px;
            color: var(--text-primary);
            letter-spacing: 1px;
        }

        .empty p {
            color: var(--text-muted);
            font-size: 13px;
            max-width: 280px;
            line-height: 1.5;
        }

        .quick-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 24px;
            justify-content: center;
        }

        .quick-btn {
            padding: 10px 16px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 24px;
            color: var(--text-primary);
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .quick-btn:hover {
            background: var(--bg-hover);
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        /* Input Area */
        .input-area {
            padding: 14px;
            background: rgba(22, 22, 29, 0.98);
            backdrop-filter: blur(20px);
            border-top: 1px solid var(--border);
        }

        .input-row {
            display: flex;
            gap: 10px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 6px 6px 6px 16px;
            align-items: flex-end;
            transition: all 0.2s ease;
        }

        .input-row:focus-within {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15);
        }

        .input {
            flex: 1;
            background: transparent;
            border: none;
            color: var(--text-primary);
            font-size: 14px;
            padding: 10px 0;
            resize: none;
            max-height: 120px;
            font-family: inherit;
            line-height: 1.6;
            font-weight: 400;
        }

        .input::placeholder { color: var(--text-muted); }
        .input:focus { outline: none; }

        .send-btn {
            padding: 10px 18px;
            border: 1px solid var(--border);
            background: var(--bg-elevated);
            color: var(--text-primary);
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s ease;
            flex-shrink: 0;
            font-family: inherit;
        }

        .send-btn:hover {
            background: var(--bg-hover);
            border-color: var(--border-light);
        }

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

        .send-btn.stop {
            background: var(--bg-tertiary);
            border-color: var(--text-muted);
        }

        /* Token Usage */
        .usage {
            font-size: 10px;
            color: var(--text-muted);
            text-align: right;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid var(--border);
        }

        /* Settings Modal */
        .modal {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.85);
            z-index: 1000;
            padding: 16px;
            overflow-y: auto;
            backdrop-filter: blur(4px);
        }

        .modal.open {
            display: flex;
            align-items: flex-start;
            justify-content: center;
            animation: modalIn 0.2s ease;
        }

        @keyframes modalIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background: var(--bg-secondary);
            border: 1px solid var(--border);
            border-radius: 20px;
            width: 100%;
            max-width: 380px;
            margin-top: 20px;
            overflow: hidden;
            animation: slideUp 0.3s ease;
        }

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

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

        .modal-title {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .close-btn {
            padding: 6px 12px;
            border: 1px solid var(--border);
            background: var(--bg-tertiary);
            color: var(--text-secondary);
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.2s ease;
            font-family: inherit;
        }

        .close-btn:hover { background: var(--danger); color: white; border-color: var(--danger); }

        .modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .setting-group { margin-bottom: 20px; }

        .setting-label {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            font-weight: 600;
            color: var(--text-secondary);
            margin-bottom: 8px;
        }

        .setting-input {
            width: 100%;
            padding: 12px 14px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 13px;
            font-family: 'JetBrains Mono', monospace;
            transition: all 0.2s ease;
        }

        .setting-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15);
        }

        .key-status {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 11px;
            color: var(--text-muted);
            margin-top: 6px;
        }

        .status-dot { width: 8px; height: 8px; border-radius: 50%; }
        .status-dot.ok { background: var(--success); box-shadow: 0 0 8px var(--success); }
        .status-dot.no { background: var(--danger); }

        /* Error */
        .error-msg {
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 12px 16px;
            color: var(--text-secondary);
            font-size: 13px;
            margin: 12px 0;
            display: flex;
            align-items: center;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            20% { transform: translateX(-6px); }
            40% { transform: translateX(6px); }
            60% { transform: translateX(-4px); }
            80% { transform: translateX(4px); }
        }
    </style>
</head>
<body>
    <div class="app">
        <header class="header">
            <div class="header-top">
                <div class="logo">
                    <img src="${logoUri}" alt="Axion AI" class="logo-img" />
                    <span class="logo-text">Axion AI</span>
                </div>
                <div class="header-actions">
                    <button class="icon-btn" id="historyBtn" title="Chat History">History</button>
                    <button class="icon-btn" id="newChatBtn" title="New Chat">New Chat</button>
                    <button class="icon-btn" id="settingsBtn" title="Settings">Settings</button>
                </div>
            </div>

            <div class="model-row">
                <div class="select-wrap">
                    <select class="select" id="modelSelect"><option>Loading models...</option></select>
                </div>
            </div>

            <div class="mode-selector-container">
                <div class="mode-selector-label">Modes</div>
                <div class="mode-tabs">
                    <button class="mode-tab active" data-mode="agent" title="Standard agent with read/write capabilities">Agent</button>
                    <button class="mode-tab" data-mode="ask" title="Read-only assistant for questions">Ask</button>
                    <button class="mode-tab" data-mode="library" title="Specialized library development">Library</button>
                    <button class="mode-tab" data-mode="swarm" title="Multi-AI swarm intelligence consensus">Swarm</button>
                    <button class="mode-tab" data-mode="evolution" title="Code evolution through generations">Evolution</button>
                    <button class="mode-tab" data-mode="quantum" title="Quantum code optimization">Quantum</button>
                    <button class="mode-tab" data-mode="neural" title="Neural architecture search">Neural</button>
                    <button class="mode-tab" data-mode="timetravel" title="Time travel debugging">Time Travel</button>
                    <button class="mode-tab" data-mode="predictive" title="Predictive coding assistant">Predictive</button>
                    <button class="mode-tab" data-mode="mindmeld" title="Deep style understanding">Mind Meld</button>
                    <button class="mode-tab" data-mode="parallel" title="Parallel universe testing">Parallel</button>
                    <button class="mode-tab" data-mode="dna" title="Code DNA analysis">DNA</button>
                    <button class="mode-tab" data-mode="collaborative" title="Multi-AI collaboration">Collaborative</button>
                </div>
            </div>
        </header>

        <div class="main-content">
            <aside class="sidebar" id="sidebar">
                <div class="sidebar-header">
                    <span class="sidebar-title">History</span>
                    <button class="icon-btn" id="closeSidebar" style="padding:6px 10px;font-size:11px;">Close</button>
                </div>
                <div class="sidebar-content" id="conversationList"></div>
            </aside>

            <div class="chat-area">
                <div class="chat" id="chat">
                    <div class="empty" id="empty">
                        <div class="empty-icon">—</div>
                        <h3>Axion AI</h3>
                        <p>Your intelligent coding companion. Choose a mode and start building.</p>
                        <div class="quick-actions">
                            <button class="quick-btn" data-prompt="Explain this codebase structure">Explain</button>
                            <button class="quick-btn" data-prompt="Find and fix bugs in my code">Debug</button>
                            <button class="quick-btn" data-prompt="Generate code for">Create</button>
                            <button class="quick-btn" data-prompt="Refactor and optimize this code">Refactor</button>
                        </div>
                    </div>
                </div>

                <div class="typing" id="typing">
                    <div class="avatar" style="background: var(--bg-elevated); border: 1px solid var(--border);">AI</div>
                    <div class="typing-dots">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                </div>

                <div class="input-area">
                    <div class="input-row">
                        <textarea class="input" id="input" placeholder="Ask Axion AI anything..." rows="1"></textarea>
                        <button class="send-btn" id="sendBtn" title="Send">Send</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="settingsModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">Settings</h2>
                <button class="close-btn" id="closeSettings">Close</button>
            </div>
            <div class="modal-body" id="settingsBody"></div>
        </div>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        let currentMode = 'agent', currentModel = '', isGenerating = false, providers = [];
        let currentStreamBubble = null, conversations = [], currentConversationId = null;

        const chat = document.getElementById('chat');
        const empty = document.getElementById('empty');
        const input = document.getElementById('input');
        const sendBtn = document.getElementById('sendBtn');
        const modelSelect = document.getElementById('modelSelect');
        const typing = document.getElementById('typing');
        const settingsModal = document.getElementById('settingsModal');
        const settingsBody = document.getElementById('settingsBody');
        const sidebar = document.getElementById('sidebar');
        const conversationList = document.getElementById('conversationList');

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

        // Mode tabs
        document.querySelectorAll('.mode-tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.mode-tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                currentMode = tab.dataset.mode;
                vscode.postMessage({ type: 'setMode', payload: { mode: currentMode } });
            });
        });

        modelSelect.addEventListener('change', () => {
            currentModel = modelSelect.value;
            vscode.postMessage({ type: 'setModel', payload: { modelId: currentModel } });
        });

        function send() {
            const text = input.value.trim();
            if (!text || isGenerating) return;
            vscode.postMessage({ type: 'sendMessage', payload: { content: text } });
            input.value = '';
            input.style.height = 'auto';
            empty.style.display = 'none';
        }

        sendBtn.addEventListener('click', () => {
            if (isGenerating) {
                vscode.postMessage({ type: 'stopGeneration' });
            } else {
                send();
            }
        });

        input.addEventListener('keydown', e => {
            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
        });

        input.addEventListener('input', () => {
            input.style.height = 'auto';
            input.style.height = Math.min(input.scrollHeight, 120) + 'px';
        });

        // Sidebar
        document.getElementById('historyBtn').addEventListener('click', () => sidebar.classList.toggle('open'));
        document.getElementById('closeSidebar').addEventListener('click', () => sidebar.classList.remove('open'));

        // Settings
        document.getElementById('settingsBtn').addEventListener('click', () => settingsModal.classList.add('open'));
        document.getElementById('closeSettings').addEventListener('click', () => settingsModal.classList.remove('open'));
        settingsModal.addEventListener('click', e => { if (e.target === settingsModal) settingsModal.classList.remove('open'); });

        document.getElementById('newChatBtn').addEventListener('click', () => vscode.postMessage({ type: 'newChat' }));

        document.querySelectorAll('.quick-btn').forEach(btn => {
            btn.addEventListener('click', () => { input.value = btn.dataset.prompt; input.focus(); });
        });

        window.addEventListener('message', e => {
            const msg = e.data;
            switch (msg.type) {
                case 'init': initUI(msg.payload); break;
                case 'userMessage': addMessage('user', msg.payload.content); break;
                case 'streamChunk': updateStream(msg.payload.fullContent); break;
                case 'streamComplete': finalizeStream(msg.payload); break;
                case 'generationStarted': setGenerating(true); break;
                case 'generationEnded': setGenerating(false); break;
                case 'generationStopped': setGenerating(false); if(currentStreamBubble) currentStreamBubble.innerHTML = '<em>Generation stopped</em>'; currentStreamBubble = null; break;
                case 'error': showError(msg.payload.message); setGenerating(false); break;
                case 'newChatCreated': currentConversationId = msg.payload.conversationId; conversations = msg.payload.conversations; renderConversations(); clearChat(); break;
                case 'conversationLoaded': loadConversation(msg.payload); break;
                case 'conversationDeleted': conversations = msg.payload.conversations; renderConversations(); if(msg.payload.conversationId === currentConversationId) clearChat(); break;
                case 'apiKeySet': updateKeyStatus(msg.payload.provider, true); break;
            }
        });

        function initUI(data) {
            providers = data.providers;
            currentModel = data.currentModel;
            currentMode = data.currentMode;
            conversations = data.conversations || [];
            currentConversationId = data.currentConversationId;

            // Build model select
            const modelsByProvider = {};
            data.models.forEach(m => {
                if (!modelsByProvider[m.provider]) modelsByProvider[m.provider] = [];
                modelsByProvider[m.provider].push(m);
            });

            modelSelect.innerHTML = '';
            for (const [providerId, models] of Object.entries(modelsByProvider)) {
                const provider = providers.find(p => p.id === providerId);
                const optgroup = document.createElement('optgroup');
                optgroup.label = provider?.name || providerId;
                models.forEach(m => {
                    const opt = document.createElement('option');
                    opt.value = m.id;
                    opt.textContent = m.name + (m.supportsThinking ? ' (Thinking)' : '') + (m.supportsVision ? ' (Vision)' : '');
                    if (m.id === currentModel) opt.selected = true;
                    optgroup.appendChild(opt);
                });
                modelSelect.appendChild(optgroup);
            }

            // Set mode
            document.querySelectorAll('.mode-tab').forEach(t => {
                t.classList.toggle('active', t.dataset.mode === currentMode);
            });

            // Build settings
            buildSettings(data.apiKeys);

            // Render conversations
            renderConversations();

            // Load existing messages
            if (data.messages && data.messages.length > 0) {
                empty.style.display = 'none';
                data.messages.forEach(m => addMessage(m.role, m.content, {}, false));
            }
        }

        function buildSettings(apiKeys) {
            const providerIcons = { anthropic: 'A', openai: 'O', google: 'G', xai: 'X', deepseek: 'D', mistral: 'M' };
            settingsBody.innerHTML = '';
            providers.forEach(p => {
                const hasKey = apiKeys[p.id];
                const div = document.createElement('div');
                div.className = 'setting-group';
                div.innerHTML = \`
                    <label class="setting-label">\${p.name}</label>
                    <input type="password" class="setting-input" data-provider="\${p.id}" placeholder="Enter your API key...">
                    <div class="key-status">
                        <span class="status-dot \${hasKey ? 'ok' : 'no'}"></span>
                        <span>\${hasKey ? 'Configured' : 'Not configured'}</span>
                    </div>
                \`;
                settingsBody.appendChild(div);
                div.querySelector('input').addEventListener('change', function() {
                    if (this.value) vscode.postMessage({ type: 'setApiKey', payload: { provider: p.id, key: this.value } });
                });
            });
        }

        function renderConversations() {
            conversationList.innerHTML = '';
            conversations.forEach(c => {
                const div = document.createElement('div');
                div.className = 'conversation-item' + (c.id === currentConversationId ? ' active' : '');
                div.innerHTML = \`
                    <span class="conversation-title">\${c.title}</span>
                    <button class="conversation-delete" data-id="\${c.id}">Delete</button>
                \`;
                div.addEventListener('click', (e) => {
                    if (!e.target.classList.contains('conversation-delete')) {
                        vscode.postMessage({ type: 'loadConversation', payload: { conversationId: c.id } });
                        sidebar.classList.remove('open');
                    }
                });
                div.querySelector('.conversation-delete').addEventListener('click', (e) => {
                    e.stopPropagation();
                    vscode.postMessage({ type: 'deleteConversation', payload: { conversationId: c.id } });
                });
                conversationList.appendChild(div);
            });
        }

        function loadConversation(data) {
            currentConversationId = data.conversationId;
            currentMode = data.mode;
            
            document.querySelectorAll('.mode-tab').forEach(t => {
                t.classList.toggle('active', t.dataset.mode === currentMode);
            });
            
            modelSelect.value = data.modelId;
            
            clearChat();
            if (data.messages && data.messages.length > 0) {
                empty.style.display = 'none';
                data.messages.forEach(m => addMessage(m.role, m.content, {}, false));
            }
            
            renderConversations();
        }

        function updateKeyStatus(provider, configured) {
            const group = settingsBody.querySelector(\`[data-provider="\${provider}"]\`)?.closest('.setting-group');
            if (group) {
                const dot = group.querySelector('.status-dot');
                const text = group.querySelector('.key-status span:last-child');
                dot.className = 'status-dot ' + (configured ? 'ok' : 'no');
                text.textContent = configured ? 'Configured' : 'Not configured';
            }
        }

        function addMessage(role, content, extra = {}, animate = true) {
            empty.style.display = 'none';
            
            const div = document.createElement('div');
            div.className = 'msg ' + role;
            if (!animate) div.style.animation = 'none';

            const avatar = document.createElement('div');
            avatar.className = 'avatar';
            avatar.textContent = role === 'assistant' ? 'AI' : 'You';

            const bubble = document.createElement('div');
            bubble.className = 'bubble';

            if (role === 'assistant') {
                bubble.innerHTML = marked.parse(content);
                processCodeBlocks(bubble);
            } else {
                bubble.textContent = content;
            }

            if (extra.changes && extra.changes.length > 0) {
                const changesDiv = document.createElement('div');
                changesDiv.className = 'changes';
                extra.changes.forEach(c => changesDiv.appendChild(createChangeCard(c)));
                bubble.appendChild(changesDiv);
            }

            if (extra.usage) {
                const usage = document.createElement('div');
                usage.className = 'usage';
                usage.innerHTML = \`Tokens: <strong>\${extra.usage.totalTokens?.toLocaleString() || '?'}</strong> (Input: \${extra.usage.promptTokens?.toLocaleString() || '?'} | Output: \${extra.usage.completionTokens?.toLocaleString() || '?'})\`;
                bubble.appendChild(usage);
            }

            div.appendChild(avatar);
            div.appendChild(bubble);
            chat.appendChild(div);
            scrollToBottom();

            return bubble;
        }

        function updateStream(content) {
            if (!currentStreamBubble) {
                empty.style.display = 'none';
                const div = document.createElement('div');
                div.className = 'msg assistant';
                div.innerHTML = '<div class="avatar" style="background: var(--bg-elevated); border: 1px solid var(--border);">AI</div><div class="bubble"></div>';
                chat.appendChild(div);
                currentStreamBubble = div.querySelector('.bubble');
            }
            currentStreamBubble.innerHTML = marked.parse(content);
            scrollToBottom();
        }

        function finalizeStream(data) {
            if (currentStreamBubble) {
                currentStreamBubble.innerHTML = marked.parse(data.content);
                processCodeBlocks(currentStreamBubble);

                if (data.changes && data.changes.length > 0) {
                    const changesDiv = document.createElement('div');
                    changesDiv.className = 'changes';
                    data.changes.forEach(c => changesDiv.appendChild(createChangeCard(c)));
                    currentStreamBubble.appendChild(changesDiv);
                }

                if (data.usage) {
                    const usage = document.createElement('div');
                    usage.className = 'usage';
                    usage.innerHTML = \`Tokens: <strong>\${data.usage.totalTokens?.toLocaleString() || '?'}</strong> (Input: \${data.usage.promptTokens?.toLocaleString() || '?'} | Output: \${data.usage.completionTokens?.toLocaleString() || '?'})\`;
                    currentStreamBubble.appendChild(usage);
                }

                currentStreamBubble = null;
            }
            scrollToBottom();
        }

        function processCodeBlocks(container) {
            container.querySelectorAll('pre').forEach(pre => {
                if (pre.querySelector('.code-header')) return;

                const code = pre.querySelector('code');
                const lang = code?.className.match(/language-(\\w+)/)?.[1] || 'code';
                const codeText = code?.textContent || '';

                // Highlight
                if (code && lang !== 'code') {
                    try { hljs.highlightElement(code); } catch(e) {}
                }

                const header = document.createElement('div');
                header.className = 'code-header';
                header.innerHTML = \`
                    <span class="code-lang">\${lang}</span>
                    <div class="code-actions">
                        <button class="code-btn copy-btn">Copy</button>
                        <button class="code-btn insert-btn">Insert</button>
                    </div>
                \`;

                header.querySelector('.copy-btn').addEventListener('click', () => {
                    vscode.postMessage({ type: 'copyToClipboard', payload: { text: codeText } });
                });

                header.querySelector('.insert-btn').addEventListener('click', () => {
                    vscode.postMessage({ type: 'insertAtCursor', payload: { text: codeText } });
                });

                pre.insertBefore(header, pre.firstChild);
            });
        }

        function createChangeCard(change) {
            const card = document.createElement('div');
            card.className = 'change-card';
                card.innerHTML = \`
                <div class="change-header">
                    <span class="change-path">\${change.filePath}</span>
                    <div class="change-actions">
                        <button class="change-btn \${change.applied ? 'applied' : 'apply'}" data-id="\${change.id}" \${change.applied ? 'disabled' : ''}>
                            \${change.applied ? 'Applied' : 'Apply'}
                        </button>
                        \${change.applied ? '<button class="change-btn revert" data-id="' + change.id + '">Revert</button>' : ''}
                    </div>
                </div>
            \`;

            card.querySelector('.apply')?.addEventListener('click', function() {
                vscode.postMessage({ type: 'applyChange', payload: { changeId: this.dataset.id } });
            });

            card.querySelector('.revert')?.addEventListener('click', function() {
                vscode.postMessage({ type: 'revertChange', payload: { changeId: this.dataset.id } });
            });

            return card;
        }

        function setGenerating(generating) {
            isGenerating = generating;
            typing.classList.toggle('visible', generating);
            sendBtn.innerHTML = generating ? 'Stop' : 'Send';
            sendBtn.classList.toggle('stop', generating);
            sendBtn.title = generating ? 'Stop' : 'Send';
            if (generating) scrollToBottom();
        }

        function showError(message) {
            const err = document.createElement('div');
            err.className = 'error-msg';
            err.innerHTML = 'Error: ' + message;
            chat.appendChild(err);
            scrollToBottom();
        }

        function clearChat() {
            chat.innerHTML = '';
            chat.appendChild(empty);
            empty.style.display = 'flex';
            currentStreamBubble = null;
        }

        function scrollToBottom() { chat.scrollTop = chat.scrollHeight; }
    </script>
</body>
</html>`;
    }
}
exports.AxionAIViewProvider = AxionAIViewProvider;
//# sourceMappingURL=AxionAIViewProvider.js.map