const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const { ModeUtils, QUICK_ACTIONS } = require('./mode-utils');
const { getLiveUIPreview } = require('./live-ui-preview');

/**
 * BUILD Mode V3 - AI-Powered Project Generation with Streaming
 * 
 * Features (Competitor-level like Cursor, Windsurf, Copilot):
 * - @ mentions for files/folders (@file, @folder, @workspace)
 * - LIVE UI PREVIEW - Visual preview of built HTML/CSS/JS projects
 * - Smart intent detection (analyze vs build vs modify)
 * - Streaming progress updates
 * - Automatic folder/file detection from message
 * - Apply changes with undo support
 * - Conversation history awareness
 */
class BuildMode {
    constructor(aiService) {
        this.aiService = aiService;
        this.webviewProvider = null;
        this.utils = new ModeUtils();
    }

    setWebviewProvider(provider) {
        this.webviewProvider = provider;
        this.utils.setWebviewProvider(provider);
    }

    async processMessage(message, context) {
        try {
            console.log('🔨 BUILD MODE V3: Processing message:', message);
            
            // Get workspace folder path
            const workspaceFolders = vscode.workspace.workspaceFolders;
            let workspacePath = '/tmp';
            if (workspaceFolders && workspaceFolders[0] && workspaceFolders[0].uri) {
                workspacePath = workspaceFolders[0].uri.fsPath;
            }

            // Parse @ mentions first
            this.utils.streamThought('Parsing @ mentions...', 'thinking');
            const mentions = await this.utils.parseAtMentions(message, workspacePath);
            
            // CRITICAL: Check user intent FIRST before assuming creation
            const intentType = this.detectUserIntent(mentions.cleanMessage);
            console.log('🎯 Detected user intent:', intentType);
            
            // Handle based on intent
            if (intentType === 'analysis') {
                return await this.handleAnalysisRequest(message, context, workspacePath, mentions);
            } else if (intentType === 'question') {
                return await this.handleQuestionRequest(message, context, mentions);
            } else if (intentType === 'modification') {
                return await this.handleModificationRequest(message, context, workspacePath, mentions);
            } else if (intentType === 'creation') {
                return await this.handleNewProjectRequest(message, context, workspacePath, mentions);
            } else if (intentType === 'followup') {
                // Follow-up messages should always include full history context
                return await this.handleFollowUpRequest(message, context, workspacePath, mentions);
            } else {
                return await this.handleAmbiguousRequest(message, context, workspacePath, mentions);
            }

        } catch (error) {
            console.error('❌ BUILD MODE V3 Error:', error);
            this.utils.streamThought(`Error: ${error.message}`, 'error');
            return {
                success: false,
                content: `## ❌ Build Error\n\nFailed to process request: ${error.message}`,
                actions: []
            };
        }
    }

    /**
     * CRITICAL: Detect what the user actually wants before taking action
     * This prevents creating projects when user wants to analyze
     */
    detectUserIntent(message) {
        const lowerMessage = message.toLowerCase();
        
        // Follow-up intent - user is continuing a conversation
        // These should always route to AI with history context
        const followUpPatterns = [
            /\bfollow\s*up\b/i,
            /\bcontinue\b/i,
            /\bproceed\b/i,
            /\bgo\s+ahead\b/i,
            /\bdo\s+(it|that|this)\b/i,
            /\byes\b/i,
            /\blet'?s\s+(do|go|start)\b/i,
            /\bplease\s+do\b/i,
            /\bnext\s+step/i,
            /\bstart\s+(with|on)\s+\d/i,  // "start with 1" or "start on step 1"
            /^\d+$/,  // Just a number (choosing option)
            /^(ok|okay|sure|yep|yeah)$/i
        ];
        
        // Analysis intent - user wants to understand/review existing code
        const analysisPatterns = [
            /\b(analy[sz]e|analy[sz]is)\b/i,
            /\b(review|examine|inspect|check)\b/i,
            /\b(explain|describe|overview)\b/i,
            /\b(what\s+is|what\s+does|how\s+does)\b/i,
            /\b(understand|look\s+at)\b/i,
            /\bgive\s+me\s+(an?\s+)?(overview|summary|explanation)\b/i,
            /\btell\s+me\s+about\b/i,
            /\bshow\s+me\b/i
        ];
        
        // Question intent - user is asking something
        const questionPatterns = [
            /\?$/,
            /^(what|how|why|when|where|which|who|can|could|would|should|is|are|do|does)\s/i,
            /\bhelp\s+me\s+understand\b/i
        ];
        
        // Creation intent - user explicitly wants to BUILD something new
        const creationPatterns = [
            /\b(create|build|make|generate|scaffold|initialize|init|setup|start)\s+(a\s+)?(new\s+)?/i,
            /\b(new\s+project|new\s+app|new\s+application)\b/i,
            /\bgive\s+me\s+(a\s+)?code\s+for\b/i,
            /\bwrite\s+(me\s+)?(a\s+)?(code|program|script|app)\b/i,
            /\bimplement\s+(a\s+)?/i
        ];
        
        // Modification intent - user wants to change existing code
        const modificationPatterns = [
            /\b(modify|update|change|edit|fix|refactor|improve|enhance)\b/i,
            /\bbroken\b/i,
            /does\s+not\s+work/i,
            /not\s+working/i,
            /has\s+errors?/i,
            /syntax\s+error/i,
            /javascript\s+error/i,
            /lacks?\s+/i,
            /missing\s+/i,
            /no\s+.+\s+visible/i,
            /\b(add|remove|delete)\s+\w+\s+(to|from)\b/i,
            /\bmake\s+(it|the|this)\b/i,
            /\bstyle\s+.+\s+(as|like|with)\b/i,
            /\bconvert\s+/i
        ];
        
        // Check for follow-up patterns FIRST (short messages that refer to previous context)
        if (followUpPatterns.some(p => p.test(message))) {
            console.log('🔄 Intent: FOLLOW-UP detected - will use history context');
            return 'followup';
        }
        
        // Check in priority order (most specific first)
        // First check if user wants to analyze/understand
        if (analysisPatterns.some(p => p.test(message))) {
            console.log('🔍 Intent: ANALYSIS detected');
            return 'analysis';
        }
        
        // Check for modification of existing code
        if (modificationPatterns.some(p => p.test(message))) {
            console.log('🔧 Intent: MODIFICATION detected');
            return 'modification';
        }
        
        // Check for explicit creation keywords
        if (creationPatterns.some(p => p.test(message))) {
            console.log('🔨 Intent: CREATION detected');
            return 'creation';
        }
        
        // Check for questions
        if (questionPatterns.some(p => p.test(message))) {
            console.log('❓ Intent: QUESTION detected');
            return 'question';
        }
        
        // Ambiguous - let AI decide with history context
        console.log('🤔 Intent: AMBIGUOUS - will route to AI with history');
        return 'ambiguous';
    }

    /**
     * Handle analysis requests - user wants to understand existing code
     * Uses ModeUtils for @ mentions and folder detection
     */
    async handleAnalysisRequest(message, context, workspacePath, mentions = null) {
        console.log('🔍 Handling ANALYSIS request with AI');
        
        this.utils.streamThought('Analyzing your code...', 'analyzing');
        this.sendStreamUpdate('## 🔍 Analyzing...\n\n');
        
        // Parse @ mentions if not already done
        if (!mentions) {
            mentions = await this.utils.parseAtMentions(message, workspacePath);
        }
        
        // Smart folder detection from message
        const detected = await this.utils.detectFilesAndFolders(mentions.cleanMessage, workspacePath);
        
        // Combine all files and folders
        const allFiles = [...mentions.files, ...detected.files];
        const allFolders = [...mentions.folders, ...detected.folders];
        
        // Build context for AI
        let folderContents = '';
        
        // Process explicitly mentioned or detected folders
        if (allFolders.length > 0) {
            for (const folder of allFolders) {
                this.utils.streamFileRead(folder.name, folder.fileContents?.length || 0);
                folderContents += `\n\n## 📁 Folder: ${folder.name}\n`;
                folderContents += `**Contents:** ${folder.summary}\n\n`;
                
                for (const file of folder.fileContents || []) {
                    this.sendStreamUpdate(`  📄 Read: ${file.name} (${file.size} bytes)\n`);
                    folderContents += `### ${file.name}\n`;
                    folderContents += `\`\`\`${file.language}\n${file.content}\n\`\`\`\n\n`;
                }
            }
        }
        
        // Process explicitly mentioned files
        if (allFiles.length > 0) {
            folderContents += '\n\n## 📄 Referenced Files:\n\n';
            for (const file of allFiles) {
                this.utils.streamFileRead(file.name, file.content?.length || 0);
                folderContents += `### ${file.name}\n`;
                folderContents += `\`\`\`${file.language}\n${file.content}\n\`\`\`\n\n`;
            }
        }
        
        // If nothing detected, scan workspace and READ actual file contents
        if (allFolders.length === 0 && allFiles.length === 0) {
            this.sendStreamUpdate('*Scanning workspace for relevant files...*\n\n');
            try {
                const items = fs.readdirSync(workspacePath, { withFileTypes: true });
                const codeExtensions = ['.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.css', '.html', '.json', '.vue', '.svelte'];
                
                folderContents = '\n\n## 📁 Workspace Analysis:\n\n';
                let filesRead = 0;
                const maxFiles = 10;
                const maxFileSize = 10000; // 10KB per file
                
                for (const item of items) {
                    if (item.name.startsWith('.') || item.name === 'node_modules') continue;
                    
                    if (item.isFile()) {
                        const ext = path.extname(item.name).toLowerCase();
                        if (codeExtensions.includes(ext) && filesRead < maxFiles) {
                            const filePath = path.join(workspacePath, item.name);
                            try {
                                const content = fs.readFileSync(filePath, 'utf8');
                                const truncated = content.length > maxFileSize ? content.substring(0, maxFileSize) + '\n... (truncated)' : content;
                                const lang = ext.replace('.', '');
                                folderContents += `### 📄 ${item.name}\n`;
                                folderContents += `\`\`\`${lang}\n${truncated}\n\`\`\`\n\n`;
                                this.sendStreamUpdate(`  📄 Read: ${item.name}\n`);
                                filesRead++;
                            } catch (e) { /* skip unreadable files */ }
                        }
                    } else if (item.isDirectory()) {
                        folderContents += `- 📁 ${item.name}/\n`;
                    }
                }
                
                if (filesRead === 0) {
                    folderContents += '\n*No code files found in root. Use @folder:name to analyze a specific folder*';
                }
            } catch (e) { /* ignore */ }
        }
        
        // Build conversation history context
        const historyContext = this.utils.buildAIContext({
            history: context.history
        });
        
        this.utils.streamThought('Generating analysis...', 'generating');
        this.sendStreamUpdate('\n*Generating analysis...*\n\n');
        
        // Build analysis prompt with full context
        const prompt = `You are Vigthoria AI, an expert code analyzer. Analyze the code/project the user is asking about.
${historyContext}

**Current User Request:** "${message}"

**Workspace Path:** ${workspacePath}
${folderContents}

**INSTRUCTIONS:**
1. Provide a detailed analysis of the code/project
2. Identify the purpose and structure
3. Point out any issues or improvements
4. Give specific, actionable recommendations
5. Reference specific files and line numbers where relevant
6. If the user asks for an enhancement plan, provide concrete steps

**CRITICAL OUTPUT REQUIREMENTS:**
- Output ONLY plain text with Markdown formatting
- Start your response with a heading like "## Analysis" or "## Overview"
- Use headers (##, ###) for sections
- Use bullet points (-) for lists
- Include code examples in \`\`\`language blocks where helpful
- NEVER output JSON, XML, or structured data formats
- NEVER wrap your response in \`\`\`json blocks
- This is a direct conversation with the user, not a data export

Begin your analysis now:`;

        try {
            const aiResponse = await this.aiService.processMessage(prompt, {
                mode: 'build',
                model: context.model || 'vigthoria-v3-code-30b',
                ...context
            });

            this.utils.streamThought('Done!', 'complete');
            let responseContent = aiResponse.content || aiResponse.response || 'Analysis complete.';
            
            // Post-process: Convert JSON responses to markdown if AI ignored instructions
            responseContent = this.convertJsonToMarkdown(responseContent);
            
            // Filter out any remaining tool call output
            responseContent = this.filterToolCalls(responseContent);
            
            return {
                success: true,
                content: responseContent,
                actions: [{
                    type: 'follow_up',
                    suggestions: [
                        'How can I improve this?',
                        'Are there any bugs?',
                        'Suggest refactoring',
                        'Generate tests for this'
                    ]
                }],
                metadata: { 
                    type: 'analysis', 
                    filesAnalyzed: allFiles.length,
                    foldersAnalyzed: allFolders.length
                }
            };
        } catch (error) {
            console.error('Analysis error:', error);
            this.utils.streamThought(`Error: ${error.message}`, 'error');
            return {
                success: false,
                content: `## ⚠️ Analysis Error\n\n${error.message}`,
                actions: []
            };
        }
    }

    /**
     * Handle question requests - user is asking something
     */
    async handleQuestionRequest(message, context) {
        console.log('❓ Handling QUESTION request with AI');
        
        this.sendStreamUpdate('## 💭 Thinking...\n\n');
        
        // Build conversation history for context
        let historyContext = '';
        if (context.history && context.history.length > 0) {
            historyContext = '\n## Previous Conversation:\n';
            for (const msg of context.history) {
                const role = msg.type === 'user' ? 'User' : 'AI';
                const content = msg.content || '';
                if (content) {
                    historyContext += `**${role}:** ${content.substring(0, 500)}${content.length > 500 ? '...' : ''}\n\n`;
                }
            }
        }
        
        // Build a clean prompt that prevents JSON tool output
        const prompt = `You are Vigthoria AI, a helpful coding assistant. Answer the user's question directly.
${historyContext}
**User Question:** "${message}"

**IMPORTANT:** 
- Respond in plain text/markdown format
- Do NOT output JSON, tool calls, or {"tool": ...} structures
- Give a clear, helpful answer
- If the question refers to previous conversation, use the context above

**Your Answer:**`;

        try {
            const aiResponse = await this.aiService.processMessage(prompt, {
                mode: 'build',
                model: context.model || 'vigthoria-v3-code-30b',
                ...context
            });

            return {
                success: true,
                content: aiResponse.content || aiResponse.response || 'I\'m here to help!',
                actions: [],
                metadata: { type: 'question' }
            };
        } catch (error) {
            return {
                success: false,
                content: `## ⚠️ Error\n\n${error.message}`,
                actions: []
            };
        }
    }

    /**
     * Handle ambiguous requests - let AI determine what user wants
     */
    async handleAmbiguousRequest(message, context, workspacePath) {
        console.log('🤔 Handling AMBIGUOUS request - asking AI');
        
        this.sendStreamUpdate('## 🤖 Processing your request...\n\n');
        
        // Build conversation history for context
        let historyContext = '';
        if (context.history && context.history.length > 0) {
            historyContext = '\n## Previous Conversation:\n';
            for (const msg of context.history) {
                const role = msg.type === 'user' ? 'User' : 'AI';
                const content = msg.content || '';
                if (content) {
                    historyContext += `**${role}:** ${content.substring(0, 500)}${content.length > 500 ? '...' : ''}\n\n`;
                }
            }
        }
        
        const prompt = `You are Vigthoria AI, a helpful coding assistant. Respond to the user's request.
${historyContext}
**User Request:** "${message}"

**IMPORTANT:**
- Respond directly in plain text/markdown format
- Do NOT output JSON, tool calls, or {"tool": ...} structures
    - If the request is actionable, take the action instead of asking the user to choose from options
    - If the request sounds like a bug report, broken file, syntax issue, or missing functionality, output the corrected code directly using FILE blocks
    - Do NOT ask "Would you like me to..." or offer menus unless a critical file path or requirement is missing
    - If the user wants code, provide actual code in code blocks or FILE blocks as appropriate
- If the user wants an explanation, explain clearly
- Be helpful and specific
- If the request refers to previous conversation, use the context above

**Your Response:**`;

        try {
            const aiResponse = await this.aiService.processMessage(prompt, {
                mode: 'build',
                model: context.model || 'vigthoria-v3-code-30b',
                ...context
            });

            return {
                success: true,
                content: aiResponse.content || aiResponse.response,
                actions: [],
                metadata: { type: 'ambiguous' }
            };
        } catch (error) {
            return {
                success: false,
                content: `## ⚠️ Error\n\n${error.message}`,
                actions: []
            };
        }
    }

    /**
     * Handle follow-up requests - user wants to continue a previous conversation
     * This gives strong emphasis to the conversation history
     */
    async handleFollowUpRequest(message, context, workspacePath, mentions = null) {
        console.log('🔄 Handling FOLLOW-UP request with full history context');
        
        this.sendStreamUpdate('## 🔄 Following up on our conversation...\n\n');
        
        // Build comprehensive conversation history
        let historyContext = '';
        if (context.history && context.history.length > 0) {
            historyContext = '\n## Our Previous Conversation:\n';
            // Use more history for follow-ups (last 10 messages)
            for (const msg of context.history.slice(-10)) {
                const role = msg.type === 'user' ? 'User' : 'AI';
                const content = msg.content || '';
                if (content) {
                    // Include more content for better context
                    historyContext += `**${role}:** ${content.substring(0, 1000)}${content.length > 1000 ? '...' : ''}\n\n`;
                }
            }
        }
        
        const prompt = `You are Vigthoria AI, a helpful coding assistant continuing a conversation with the user.

${historyContext}

**Current User Message:** "${message}"

**CRITICAL INSTRUCTIONS:**
1. You MUST refer to and continue from the previous conversation above
2. If the user says "follow up", "continue", "proceed", or similar - they want you to continue with what was discussed
3. If the previous conversation mentioned an enhancement plan or list, START IMPLEMENTING it
4. Be specific - refer to exact items from the previous conversation
5. Output in plain text/markdown format
6. Include actual code in code blocks where needed
7. Do NOT ask what they want to do next - JUST DO IT based on context
8. Do NOT output tool-call JSON, approval instructions, or "Would you like me to" menus

**Your Response (continuing from previous conversation):**`;

        try {
            const aiResponse = await this.aiService.processMessage(prompt, {
                mode: 'build',
                model: context.model || 'vigthoria-v3-code-30b',
                ...context
            });

            return {
                success: true,
                content: aiResponse.content || aiResponse.response,
                actions: [],
                metadata: { type: 'followup', historyLength: context.history?.length || 0 }
            };
        } catch (error) {
            return {
                success: false,
                content: `## ⚠️ Error\n\n${error.message}`,
                actions: []
            };
        }
    }

    isModificationRequest(message) {
        const modificationPatterns = [
            /make\s+(it|the|this)/i,
            /change\s+(the|to)/i,
            /update\s+/i,
            /modify\s+/i,
            /add\s+.+\s+to/i,
            /style\s+.+\s+(as|like|with)/i,
            /convert\s+/i,
            /in\s+a\s+.+\s+(style|theme)/i
        ];
        return modificationPatterns.some(pattern => pattern.test(message));
    }

    async handleModificationRequest(message, context, workspacePath) {
        // For modification requests, we need to use AI
        console.log('🔄 Handling modification request with AI');
        
        // Send streaming start notification
        this.sendStreamUpdate('🤖 **Analyzing your request...**\n\n');
        
        // Build AI prompt for modification
        const prompt = this.buildModificationPrompt(message, context);
        
        try {
            // Call AI service for code generation
            const aiResponse = await this.aiService.processMessage(prompt, {
                mode: 'build',
                model: context.model || 'vigthoria-v3-code-30b',
                ...context
            });

            if (!aiResponse.success) {
                return {
                    success: false,
                    content: `## ⚠️ AI Response Issue\n\n${aiResponse.content || 'Could not get AI response'}`,
                    actions: []
                };
            }

            // Parse and execute the AI's code modifications
            const modifications = this.parseAICodeResponse(aiResponse.content || aiResponse.response);
            
            if (modifications.files && modifications.files.length > 0) {
                // Apply file modifications
                const results = await this.applyFileModifications(modifications.files, workspacePath);
                
                return {
                    success: true,
                    content: this.formatModificationResponse(modifications, results),
                    actions: [],
                    metadata: {
                        type: 'modification',
                        filesModified: results.modified.length,
                        filesCreated: results.created.length
                    }
                };
            } else {
                // Just return the AI's response as guidance
                return {
                    success: true,
                    content: `## 🔨 BUILD Mode - AI Response\n\n${aiResponse.content || aiResponse.response}`,
                    actions: []
                };
            }
            
        } catch (error) {
            console.error('AI modification error:', error);
            return {
                success: false,
                content: `## ❌ AI Error\n\n${error.message}`,
                actions: []
            };
        }
    }

    async handleNewProjectRequest(message, context, workspacePath) {
        console.log('🔨 BUILD MODE: Using AI to generate project (NO templates)');
        
        // Send streaming updates
        this.sendStreamUpdate(`## 🔨 BUILD Mode - AI Project Generation\n\n`);
        await this.delay(100);
        this.sendStreamUpdate(`🤖 *AI is analyzing your request and generating custom code...*\n\n`);
        
        // Build AI prompt for code generation
        const prompt = this.buildProjectGenerationPrompt(message, workspacePath);
        
        try {
            // Call AI service for code generation
            const aiResponse = await this.aiService.processMessage(prompt, {
                mode: 'build',
                model: context.model || 'vigthoria-v3-code-30b',
                ...context
            });

            if (!aiResponse.success && !aiResponse.content && !aiResponse.response) {
                return {
                    success: false,
                    content: `## ⚠️ AI Response Issue\n\n${aiResponse.content || 'Could not get AI response. Please try again.'}`,
                    actions: []
                };
            }

            const responseContent = aiResponse.content || aiResponse.response || '';
            
            // Parse and execute the AI's generated code
            const generatedFiles = this.parseAICodeResponse(responseContent);
            
            if (generatedFiles.files && generatedFiles.files.length > 0) {
                this.sendStreamUpdate(`\n📁 **Creating ${generatedFiles.files.length} files...**\n\n`);
                
                // Create the files
                const results = await this.applyFileModifications(generatedFiles.files, workspacePath);
                
                // Stream file creation progress
                for (const file of results.created) {
                    this.sendStreamUpdate(`  ✅ Created: ${file}\n`);
                    await this.delay(50);
                }
                
                return {
                    success: true,
                    content: this.formatAIBuildResponse(generatedFiles, results, workspacePath),
                    actions: [],
                    metadata: {
                        type: 'ai-generation',
                        filesCreated: results.created.length,
                        filesModified: results.modified.length,
                        workspacePath: workspacePath
                    }
                };
            } else {
                // AI provided guidance but no file blocks - return the response
                return {
                    success: true,
                    content: `## 🔨 BUILD Mode - AI Response\n\n${responseContent}\n\n---\n💡 *Tip: If you want me to create files, be more specific like "create a calculator app with HTML, CSS, and JavaScript"*`,
                    actions: [],
                    metadata: { type: 'ai-guidance' }
                };
            }
            
        } catch (error) {
            console.error('AI project generation error:', error);
            return {
                success: false,
                content: `## ❌ AI Generation Error\n\n${error.message}\n\nPlease try again with a clearer request.`,
                actions: []
            };
        }
    }

    /**
     * Build a prompt for AI to generate complete project code
     */
    buildProjectGenerationPrompt(message, workspacePath) {
        return `You are Vigthoria AI, an expert software developer in BUILD mode. Generate complete, production-ready code based on the user's request.

## User Request:
"${message}"

## Workspace:
${workspacePath}

## Instructions:
1. Generate complete, working code for the user's request
2. Create all necessary files with proper structure
3. Include all dependencies and configurations
4. Add helpful comments in the code
5. Follow best practices for the chosen technology

## IMPORTANT - File Format:
You MUST wrap each file you create in this exact format:

--- FILE: folder/filename.ext ---
<complete file content here>
--- END FILE ---

Example:
--- FILE: my-app/index.html ---
<!DOCTYPE html>
<html>
<head><title>My App</title></head>
<body><h1>Hello World</h1></body>
</html>
--- END FILE ---

--- FILE: my-app/style.css ---
body { font-family: Arial; }
--- END FILE ---

## Generate the complete project now:`;
    }

    /**
     * Format the response for AI-generated builds
     */
    formatAIBuildResponse(generatedFiles, results, workspacePath) {
        let response = `## 🔨 BUILD Mode - Project Created!\n\n`;
        response += `**Location:** ${workspacePath}\n\n`;
        response += `### 📁 Files Created:\n\n`;
        
        // Find the main HTML file for preview
        let mainHtmlFile = null;
        
        for (const file of results.created) {
            const ext = path.extname(file).toLowerCase();
            const icon = this.getFileIcon(ext);
            response += `- ${icon} ${file}\n`;
            
            // Track HTML files for preview
            if (ext === '.html' && !mainHtmlFile) {
                mainHtmlFile = file;
            }
        }
        
        if (results.modified.length > 0) {
            response += `\n### 📝 Files Modified:\n\n`;
            for (const file of results.modified) {
                response += `- 📝 ${file}\n`;
            }
        }
        
        if (results.errors.length > 0) {
            response += `\n### ⚠️ Errors:\n\n`;
            for (const err of results.errors) {
                response += `- ❌ ${err.path}: ${err.error}\n`;
            }
        }
        
        response += `\n---\n✅ **Project ready!** ${results.created.length} files created by AI.\n`;
        
        // Add preview button if HTML file was created
        if (mainHtmlFile) {
            response += `\n### 🔍 Preview Your Project:\n\n`;
            response += `Click the button below to see your project in action!\n\n`;
            
            // Open the HTML file in Simple Browser for preview
            this.openProjectPreview(path.join(workspacePath, mainHtmlFile), workspacePath);
        }
        
        response += `\n💡 *Open the files in the explorer to review and customize.*`;
        
        return response;
    }

    /**
     * Open project preview in the Live UI Preview panel
     * Shows a visual rendering of the HTML/CSS/JS in a webview panel
     * @param {string} htmlFilePath - Full path to the main HTML file
     * @param {string} workspacePath - The workspace root path
     */
    async openProjectPreview(htmlFilePath, workspacePath) {
        try {
            console.log('🖼️ Opening Live UI Preview for:', htmlFilePath);
            
            // Get the Live UI Preview instance
            const livePreview = getLiveUIPreview(this.webviewProvider?._context);
            
            if (livePreview) {
                // Show the Live UI Preview panel with the created project
                await livePreview.showPreview(htmlFilePath, workspacePath);
                this.sendStreamUpdate(`\n🖼️ **Live UI Preview opened!** See your project rendering in the preview panel.\n`);
                console.log('✅ Live UI Preview panel opened successfully');
            } else {
                // Fallback: Try Simple Browser or external browser
                console.log('⚠️ Live UI Preview not available, using fallback');
                await this.openProjectPreviewFallback(htmlFilePath, workspacePath);
            }
            
            // Also reveal the HTML file in the editor (minimized)
            try {
                const fileUri = vscode.Uri.file(htmlFilePath);
                const document = await vscode.workspace.openTextDocument(fileUri);
                await vscode.window.showTextDocument(document, { 
                    preview: true, 
                    preserveFocus: true,
                    viewColumn: vscode.ViewColumn.One
                });
            } catch (e) {
                // Ignore file open errors
            }
            
        } catch (error) {
            console.error('❌ Preview error:', error);
            this.sendStreamUpdate(`\n⚠️ Could not open Live UI Preview: ${error.message}\n`);
            // Try fallback
            await this.openProjectPreviewFallback(htmlFilePath, workspacePath);
        }
    }

    /**
     * Fallback preview method using Simple Browser or external browser
     */
    async openProjectPreviewFallback(htmlFilePath, workspacePath) {
        try {
            const fileUri = vscode.Uri.file(htmlFilePath);
            
            // Check if Live Server extension is available
            const liveServerExtension = vscode.extensions.getExtension('ritwickdey.LiveServer');
            
            if (liveServerExtension) {
                console.log('🚀 Using Live Server for preview');
                await vscode.commands.executeCommand('liveServer.goOnline');
                this.sendStreamUpdate(`\n🌐 **Live Server started!** Preview opening in browser...\n`);
            } else {
                // Try Simple Browser
                try {
                    await vscode.commands.executeCommand('simpleBrowser.show', fileUri);
                    this.sendStreamUpdate(`\n🔍 **Preview opened** in Simple Browser panel.\n`);
                } catch (simpleBrowserError) {
                    // Open externally
                    await vscode.env.openExternal(fileUri);
                    this.sendStreamUpdate(`\n🌐 **Preview opened** in your default browser.\n`);
                }
            }
        } catch (error) {
            console.error('❌ Fallback preview error:', error);
            this.sendStreamUpdate(`\n⚠️ Could not open preview. Please open the HTML file manually.\n`);
        }
    }

    getFileIcon(ext) {
        const icons = {
            '.html': '🌐',
            '.css': '🎨',
            '.js': '⚙️',
            '.ts': '📘',
            '.json': '📋',
            '.md': '📖',
            '.py': '🐍',
            '.jsx': '⚛️',
            '.tsx': '⚛️',
            '.vue': '💚',
            '.svelte': '🔥',
            '.go': '🔵',
            '.rs': '🦀',
            '.java': '☕',
            '.php': '🐘',
            '.rb': '💎',
            '.sql': '🗃️',
            '.sh': '📜',
            '.yaml': '📄',
            '.yml': '📄',
            '.toml': '📄',
            '.env': '🔒'
        };
        return icons[ext] || '📄';
    }

    /**
     * Convert JSON responses to readable markdown if AI output JSON despite instructions
     */
    convertJsonToMarkdown(content) {
        if (!content) return content;
        
        // Check if content looks like JSON (starts with ``` json or { or [)
        const trimmed = content.trim();
        const jsonBlockMatch = trimmed.match(/^```json?\s*([\s\S]*?)```$/);
        const rawJsonMatch = trimmed.match(/^\s*[\[{]/);
        
        let jsonStr = null;
        if (jsonBlockMatch) {
            jsonStr = jsonBlockMatch[1].trim();
        } else if (rawJsonMatch) {
            jsonStr = trimmed;
        }
        
        if (!jsonStr) return content;
        
        try {
            const data = JSON.parse(jsonStr);
            return this.jsonToMarkdown(data);
        } catch (e) {
            // Not valid JSON, return original content
            return content;
        }
    }

    /**
     * Recursively convert a JSON object to markdown
     */
    jsonToMarkdown(obj, depth = 0) {
        if (obj === null || obj === undefined) return '';
        if (typeof obj === 'string') return obj;
        if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj);
        
        let md = '';
        const indent = '  '.repeat(depth);
        
        if (Array.isArray(obj)) {
            for (const item of obj) {
                if (typeof item === 'object' && item !== null) {
                    md += this.jsonToMarkdown(item, depth);
                } else {
                    md += `${indent}- ${item}\n`;
                }
            }
        } else if (typeof obj === 'object') {
            for (const [key, value] of Object.entries(obj)) {
                const formattedKey = key.replace(/([A-Z])/g, ' $1').replace(/^./, s => s.toUpperCase());
                
                if (typeof value === 'string') {
                    if (value.length > 100) {
                        md += `\n### ${formattedKey}\n${value}\n`;
                    } else {
                        md += `- **${formattedKey}:** ${value}\n`;
                    }
                } else if (Array.isArray(value)) {
                    md += `\n### ${formattedKey}\n`;
                    for (const item of value) {
                        if (typeof item === 'object' && item !== null) {
                            md += this.jsonToMarkdown(item, depth + 1);
                        } else {
                            md += `- ${item}\n`;
                        }
                    }
                } else if (typeof value === 'object' && value !== null) {
                    md += `\n## ${formattedKey}\n`;
                    md += this.jsonToMarkdown(value, depth + 1);
                } else if (value !== null && value !== undefined) {
                    md += `- **${formattedKey}:** ${value}\n`;
                }
            }
        }
        
        return md;
    }

    /**
     * Filter out tool calls from AI response - these should be internal operations
     * Users should see the RESULT of tool use, not the tool calls themselves
     */
    filterToolCalls(text) {
        if (!text || typeof text !== 'string') return text;
        
        let filtered = text;
        
        // Remove JSON tool call blocks like {"tool": "read_file", ...}
        filtered = filtered.replace(/\{[\s\n]*"tool"[\s\n]*:[\s\S]*?\}\s*/g, '');
        
        // Remove markdown formatted tool calls like "- **Tool:** read_file"
        filtered = filtered.replace(/^\s*-?\s*\*?\*?Tool\*?\*?:?\s*[a-z_]+.*$/gmi, '');
        
        // Remove "## Parameters" sections that follow tool calls
        filtered = filtered.replace(/^##\s*Parameters\s*[\s\S]*?(?=^##|\n\n\n|$)/gmi, '');
        
        // Remove lines like "- **Path:** /some/path" that are tool call parameters
        filtered = filtered.replace(/^\s*-\s*\*\*Path\*\*:\s*\/.*$/gmi, '');
        filtered = filtered.replace(/^\s*-\s*\*\*File\*\*:\s*\/.*$/gmi, '');
        
        // Remove MCP tool call syntax [tool_name params]
        filtered = filtered.replace(/\[(?:read_file|write_file|list_dir|search|grep)\s+[^\]]+\]/gi, '');
        
        // Remove "I'll use the X tool" or "Using the X tool" phrases
        filtered = filtered.replace(/^.*(?:I'll use|Using|Let me use|I will use)\s+(?:the\s+)?[a-z_]+\s+tool.*$/gmi, '');
        
        // Clean up excessive newlines
        filtered = filtered.replace(/\n{3,}/g, '\n\n');
        
        return filtered.trim();
    }

    sendStreamUpdate(text) {
        if (this.webviewProvider && this.webviewProvider._view) {
            this.webviewProvider._view.webview.postMessage({
                type: 'streamUpdate',
                data: { text: text }
            });
        }
    }

    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    buildModificationPrompt(message, context) {
        // Build conversation history for context
        let historyContext = '';
        if (context.history && context.history.length > 0) {
            historyContext = '\n\n## Previous Conversation:\n';
            for (const msg of context.history) {
                const role = msg.type === 'user' ? 'User' : 'AI';
                const content = msg.content || '';
                if (content) {
                    historyContext += `**${role}:** ${content.substring(0, 500)}${content.length > 500 ? '...' : ''}\n\n`;
                }
            }
        }

        return `You are a code modification assistant. The user wants to modify their existing project.
${historyContext}
**Current User Request:** "${message}"

IMPORTANT: If the user's request refers to something from the previous conversation (like "do the enhancement" or "fix that"), use the conversation history above to understand what they mean.

Please provide the modified code. If you need to create or modify files, format your response like this:

--- FILE: path/to/file.ext ---
<file content here>
--- END FILE ---

RULES:
1. Do NOT output JSON tool calls, execution plans, approval prompts, or option menus
2. Do NOT ask the user what to do next when the request is actionable
3. Fix the root cause and return complete contents for each changed file

Provide complete, working code that implements the user's request.`;
    }

    parseAICodeResponse(response) {
        const files = [];
        const filePattern = /---\s*FILE:\s*(.+?)\s*---\n([\s\S]*?)---\s*END\s*FILE\s*---/gi;
        let match;
        
        while ((match = filePattern.exec(response)) !== null) {
            files.push({
                path: match[1].trim(),
                content: match[2].trim()
            });
        }
        
        return {
            files: files,
            explanation: response
        };
    }

    async applyFileModifications(files, workspacePath) {
        const results = { modified: [], created: [], errors: [] };
        
        for (const file of files) {
            try {
                const fullPath = path.join(workspacePath, file.path);
                const dir = path.dirname(fullPath);
                
                // Check if file exists
                const exists = fs.existsSync(fullPath);
                
                // Create directory if needed
                if (!fs.existsSync(dir)) {
                    fs.mkdirSync(dir, { recursive: true });
                }
                
                // Write file
                fs.writeFileSync(fullPath, file.content);
                
                if (exists) {
                    results.modified.push(file.path);
                } else {
                    results.created.push(file.path);
                }
            } catch (error) {
                results.errors.push({ path: file.path, error: error.message });
            }
        }
        
        return results;
    }

    formatModificationResponse(modifications, results) {
        let response = `## 🔨 BUILD Mode - Modifications Applied\n\n`;
        
        if (results.modified.length > 0) {
            response += `### ✏️ Modified Files:\n`;
            results.modified.forEach(f => response += `- ${f}\n`);
            response += `\n`;
        }
        
        if (results.created.length > 0) {
            response += `### ➕ Created Files:\n`;
            results.created.forEach(f => response += `- ${f}\n`);
            response += `\n`;
        }
        
        if (results.errors.length > 0) {
            response += `### ⚠️ Errors:\n`;
            results.errors.forEach(e => response += `- ${e.path}: ${e.error}\n`);
            response += `\n`;
        }
        
        response += `\n---\n✅ **Modifications complete!** Refresh the file explorer to see changes.`;
        
        return response;
    }

    analyzeBuildRequest(message) {
        const projectTypes = {
            'react': /react|jsx|frontend|spa/i,
            'nodejs': /node|express|api|server|backend/i,
            'python': /python|django|flask|fastapi/i,
            'html': /html|css|javascript|website|static/i,
            'typescript': /typescript|ts|angular/i,
            'vue': /vue|nuxt/i,
            'nextjs': /next\.js|nextjs/i,
            'calculator': /calculator|calc/i
        };

        let detectedType = 'html';
        for (const [type, regex] of Object.entries(projectTypes)) {
            if (regex.test(message)) {
                detectedType = type;
                break;
            }
        }

        // Extract project name - improved regex
        let projectName = 'vigthoria-project';
        
        // Try multiple patterns
        const patterns = [
            /(?:create|build|make|generate)\s+(?:a\s+)?(?:new\s+)?["']([^"']+)["']/i,
            /(?:create|build|make|generate)\s+(?:a\s+)?(?:new\s+)?(\w+[-\w]*)\s+(?:app|project|application)/i,
            /(?:called|named)\s+["']?(\w+[-\w]*)["']?/i,
            /^(\w+[-\w]*)\s+(?:app|project|application)/i
        ];
        
        for (const pattern of patterns) {
            const match = message.match(pattern);
            if (match && match[1] && match[1].length > 1) {
                projectName = match[1].toLowerCase().replace(/\s+/g, '-');
                break;
            }
        }
        
        // If still default, use the detected type as project name
        if (projectName === 'vigthoria-project' && detectedType !== 'html') {
            projectName = `${detectedType}-app`;
        }

        return {
            type: detectedType,
            name: projectName,
            originalMessage: message,
            features: this.extractFeatures(message)
        };
    }

    extractFeatures(message) {
        const features = [];
        if (/auth|login|register/i.test(message)) features.push('authentication');
        if (/database|db|sql|mongo/i.test(message)) features.push('database');
        if (/api|rest|graphql/i.test(message)) features.push('api');
        if (/test|testing|jest|cypress/i.test(message)) features.push('testing');
        if (/docker|container/i.test(message)) features.push('docker');
        if (/dark|cyber|neon/i.test(message)) features.push('dark-theme');
        return features;
    }

    async generateProjectStructure(buildRequest, aiPlanning) {
        const structures = {
            react: this.generateReactStructure,
            nodejs: this.generateNodeStructure,
            python: this.generatePythonStructure,
            typescript: this.generateTypeScriptStructure,
            vue: this.generateVueStructure,
            nextjs: this.generateNextJSStructure,
            html: this.generateHTMLStructure,
            calculator: this.generateCalculatorStructure
        };

        const generator = structures[buildRequest.type] || structures.html;
        return generator.call(this, buildRequest, aiPlanning);
    }

    generateCalculatorStructure(buildRequest, aiPlanning) {
        const hasDarkTheme = buildRequest.features.includes('dark-theme');
        
        return [
            {
                path: `${buildRequest.name}/index.html`,
                content: this.generateCalculatorHTML(buildRequest.name),
                type: 'template'
            },
            {
                path: `${buildRequest.name}/style.css`,
                content: hasDarkTheme ? this.generateCyberCalculatorCSS() : this.generateCalculatorCSS(),
                type: 'stylesheet'
            },
            {
                path: `${buildRequest.name}/calculator.js`,
                content: this.generateCalculatorJS(),
                type: 'script'
            },
            {
                path: `${buildRequest.name}/README.md`,
                content: this.generateReadme(buildRequest.name, 'Calculator Application'),
                type: 'documentation'
            }
        ];
    }

    generateCalculatorHTML(name) {
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${name} - Calculator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="calculator">
        <div class="display">
            <div class="previous-operand"></div>
            <div class="current-operand">0</div>
        </div>
        <div class="buttons">
            <button class="span-two" data-action="clear">AC</button>
            <button data-action="delete">DEL</button>
            <button data-action="operator" data-value="/">÷</button>
            <button data-action="number" data-value="7">7</button>
            <button data-action="number" data-value="8">8</button>
            <button data-action="number" data-value="9">9</button>
            <button data-action="operator" data-value="*">×</button>
            <button data-action="number" data-value="4">4</button>
            <button data-action="number" data-value="5">5</button>
            <button data-action="number" data-value="6">6</button>
            <button data-action="operator" data-value="-">−</button>
            <button data-action="number" data-value="1">1</button>
            <button data-action="number" data-value="2">2</button>
            <button data-action="number" data-value="3">3</button>
            <button data-action="operator" data-value="+">+</button>
            <button data-action="number" data-value="0" class="span-two">0</button>
            <button data-action="decimal">.</button>
            <button data-action="equals" class="equals">=</button>
        </div>
    </div>
    <script src="calculator.js"></script>
</body>
</html>`;
    }

    generateCalculatorCSS() {
        return `/* Calculator Styles - Generated by Vigthoria AI */
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    font-family: 'Segoe UI', sans-serif;
}
.calculator {
    background: rgba(0, 0, 0, 0.9);
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
}
.display {
    background: #2d2d2d;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    text-align: right;
    min-height: 80px;
}
.previous-operand { color: rgba(255, 255, 255, 0.5); font-size: 1.2rem; min-height: 24px; }
.current-operand { color: white; font-size: 2.5rem; font-weight: 300; word-wrap: break-word; }
.buttons { display: grid; grid-template-columns: repeat(4, 75px); gap: 10px; }
button {
    height: 75px;
    border: none;
    border-radius: 15px;
    font-size: 1.5rem;
    cursor: pointer;
    background: #3d3d3d;
    color: white;
    transition: all 0.2s;
}
button:hover { background: #4d4d4d; }
button:active { transform: scale(0.95); }
button[data-action="operator"] { background: #ff9500; }
button[data-action="operator"]:hover { background: #ffaa33; }
button.equals { background: #34c759; }
button.equals:hover { background: #45d96a; }
button.span-two { grid-column: span 2; }
button[data-action="clear"] { background: #ff3b30; }
button[data-action="clear"]:hover { background: #ff5147; }`;
    }

    generateCyberCalculatorCSS() {
        return `/* Cyber Calculator Styles - Generated by Vigthoria AI */
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #0a0a0f;
    font-family: 'Orbitron', sans-serif;
    overflow: hidden;
}
body::before {
    content: '';
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: 
        radial-gradient(circle at 20% 50%, rgba(0, 255, 255, 0.1) 0%, transparent 50%),
        radial-gradient(circle at 80% 50%, rgba(255, 0, 255, 0.1) 0%, transparent 50%),
        linear-gradient(0deg, rgba(0,255,255,0.02) 1px, transparent 1px),
        linear-gradient(90deg, rgba(0,255,255,0.02) 1px, transparent 1px);
    background-size: 100% 100%, 100% 100%, 50px 50px, 50px 50px;
    pointer-events: none;
}
.calculator {
    background: linear-gradient(145deg, #0d0d12, #1a1a2e);
    border: 2px solid #00ffff;
    border-radius: 20px;
    padding: 25px;
    box-shadow: 
        0 0 20px rgba(0, 255, 255, 0.3),
        0 0 40px rgba(0, 255, 255, 0.1),
        inset 0 0 20px rgba(0, 255, 255, 0.05);
    position: relative;
}
.calculator::before {
    content: 'VIGTHORIA CALC';
    position: absolute;
    top: -25px; left: 50%;
    transform: translateX(-50%);
    font-size: 0.7rem;
    color: #00ffff;
    text-shadow: 0 0 10px #00ffff;
    letter-spacing: 3px;
}
.display {
    background: linear-gradient(145deg, #0a0a0f, #15151f);
    border: 1px solid #00ffff;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    text-align: right;
    min-height: 90px;
    box-shadow: inset 0 0 20px rgba(0, 255, 255, 0.1);
}
.previous-operand { color: #00ffff80; font-size: 1rem; min-height: 20px; letter-spacing: 2px; }
.current-operand { 
    color: #00ffff; 
    font-size: 2.5rem; 
    font-weight: 700; 
    text-shadow: 0 0 10px #00ffff, 0 0 20px #00ffff40;
    letter-spacing: 3px;
}
.buttons { display: grid; grid-template-columns: repeat(4, 70px); gap: 12px; }
button {
    height: 70px;
    border: 1px solid #333;
    border-radius: 10px;
    font-size: 1.3rem;
    font-family: 'Orbitron', sans-serif;
    cursor: pointer;
    background: linear-gradient(145deg, #1a1a2e, #0d0d12);
    color: #fff;
    transition: all 0.3s;
    text-shadow: 0 0 5px currentColor;
}
button:hover {
    border-color: #00ffff;
    box-shadow: 0 0 15px rgba(0, 255, 255, 0.5), inset 0 0 15px rgba(0, 255, 255, 0.1);
    color: #00ffff;
}
button:active { transform: scale(0.95); }
button[data-action="operator"] {
    background: linear-gradient(145deg, #2a0a3a, #1a0a2a);
    border-color: #ff00ff;
    color: #ff00ff;
}
button[data-action="operator"]:hover {
    box-shadow: 0 0 15px rgba(255, 0, 255, 0.5), inset 0 0 15px rgba(255, 0, 255, 0.1);
}
button.equals {
    background: linear-gradient(145deg, #003333, #001a1a);
    border-color: #00ff88;
    color: #00ff88;
}
button.equals:hover {
    box-shadow: 0 0 20px rgba(0, 255, 136, 0.6), inset 0 0 20px rgba(0, 255, 136, 0.1);
}
button.span-two { grid-column: span 2; }
button[data-action="clear"] {
    background: linear-gradient(145deg, #3a0a0a, #2a0505);
    border-color: #ff3333;
    color: #ff3333;
}
button[data-action="clear"]:hover {
    box-shadow: 0 0 15px rgba(255, 51, 51, 0.5), inset 0 0 15px rgba(255, 51, 51, 0.1);
}`;
    }

    generateCalculatorJS() {
        return `// Calculator Logic - Generated by Vigthoria AI
class Calculator {
    constructor() {
        this.currentOperand = '0';
        this.previousOperand = '';
        this.operation = null;
        this.shouldResetScreen = false;
        this.previousOperandElement = document.querySelector('.previous-operand');
        this.currentOperandElement = document.querySelector('.current-operand');
        this.init();
    }

    init() {
        document.querySelectorAll('button').forEach(button => {
            button.addEventListener('click', () => {
                const action = button.dataset.action;
                const value = button.dataset.value;
                switch (action) {
                    case 'number': this.appendNumber(value); break;
                    case 'operator': this.setOperation(value); break;
                    case 'equals': this.calculate(); break;
                    case 'clear': this.clear(); break;
                    case 'delete': this.delete(); break;
                    case 'decimal': this.appendDecimal(); break;
                }
                this.updateDisplay();
            });
        });
        document.addEventListener('keydown', (e) => {
            if (e.key >= '0' && e.key <= '9') this.appendNumber(e.key);
            if (e.key === '.') this.appendDecimal();
            if (['+', '-', '*', '/'].includes(e.key)) this.setOperation(e.key);
            if (e.key === 'Enter' || e.key === '=') this.calculate();
            if (e.key === 'Backspace') this.delete();
            if (e.key === 'Escape') this.clear();
            this.updateDisplay();
        });
    }

    appendNumber(number) {
        if (this.shouldResetScreen) { this.currentOperand = ''; this.shouldResetScreen = false; }
        this.currentOperand = this.currentOperand === '0' ? number : this.currentOperand + number;
    }

    appendDecimal() {
        if (this.shouldResetScreen) { this.currentOperand = '0'; this.shouldResetScreen = false; }
        if (!this.currentOperand.includes('.')) this.currentOperand += '.';
    }

    setOperation(op) {
        if (this.operation !== null) this.calculate();
        this.operation = op;
        this.previousOperand = this.currentOperand;
        this.shouldResetScreen = true;
    }

    calculate() {
        const prev = parseFloat(this.previousOperand);
        const current = parseFloat(this.currentOperand);
        if (isNaN(prev) || isNaN(current)) return;
        let result;
        switch (this.operation) {
            case '+': result = prev + current; break;
            case '-': result = prev - current; break;
            case '*': result = prev * current; break;
            case '/': result = current === 0 ? 'Error' : prev / current; break;
            default: return;
        }
        this.currentOperand = result.toString();
        this.operation = null;
        this.previousOperand = '';
        this.shouldResetScreen = true;
    }

    delete() {
        this.currentOperand = this.currentOperand.length === 1 ? '0' : this.currentOperand.slice(0, -1);
    }

    clear() {
        this.currentOperand = '0';
        this.previousOperand = '';
        this.operation = null;
    }

    updateDisplay() {
        this.currentOperandElement.textContent = this.currentOperand;
        this.previousOperandElement.textContent = this.operation ? 
            this.previousOperand + ' ' + { '+': '+', '-': '−', '*': '×', '/': '÷' }[this.operation] : '';
    }
}
const calculator = new Calculator();
console.log('🧮 Calculator initialized!');`;
    }

    generateHTMLStructure(buildRequest, aiPlanning) {
        const hasDarkTheme = buildRequest.features.includes('dark-theme');
        return [
            {
                path: `${buildRequest.name}/index.html`,
                content: this.generateGenericHTML(buildRequest.name, hasDarkTheme),
                type: 'template'
            },
            {
                path: `${buildRequest.name}/style.css`,
                content: hasDarkTheme ? this.generateCyberCSS() : this.generateGenericCSS(),
                type: 'stylesheet'
            },
            {
                path: `${buildRequest.name}/script.js`,
                content: this.generateGenericJS(buildRequest.name),
                type: 'script'
            },
            {
                path: `${buildRequest.name}/README.md`,
                content: this.generateReadme(buildRequest.name, 'Web Application'),
                type: 'documentation'
            }
        ];
    }

    generateGenericHTML(name, isDark = false) {
        const themeClass = isDark ? 'dark-cyber-theme' : '';
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${name}</title>
    <link rel="stylesheet" href="style.css">
</head>
<body class="${themeClass}">
    <div class="container">
        <header>
            <h1>${name}</h1>
        </header>
        <main>
            <p>Welcome to ${name}! Built with Vigthoria AI.</p>
        </main>
        <footer>
            <p>&copy; 2025 ${name} - Generated by Vigthoria AI</p>
        </footer>
    </div>
    <script src="script.js"></script>
</body>
</html>`;
    }

    generateGenericCSS() {
        return `/* Styles - Generated by Vigthoria AI */
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}
.container {
    background: white;
    border-radius: 16px;
    padding: 40px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
    max-width: 800px;
    width: 100%;
}
header { text-align: center; margin-bottom: 30px; }
h1 {
    color: #333;
    font-size: 2.5rem;
    font-weight: 700;
}
main { padding: 20px 0; }
p { color: #666; line-height: 1.6; }
footer { margin-top: 40px; text-align: center; color: #999; font-size: 0.9rem; }`;
    }

    generateCyberCSS() {
        return `/* Cyber Theme - Generated by Vigthoria AI */
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap');
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Orbitron', sans-serif;
    min-height: 100vh;
    background: #0a0a0f;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}
body::before {
    content: '';
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: 
        radial-gradient(circle at 20% 50%, rgba(0, 255, 255, 0.1) 0%, transparent 50%),
        radial-gradient(circle at 80% 50%, rgba(255, 0, 255, 0.1) 0%, transparent 50%),
        linear-gradient(0deg, rgba(0,255,255,0.02) 1px, transparent 1px),
        linear-gradient(90deg, rgba(0,255,255,0.02) 1px, transparent 1px);
    background-size: 100% 100%, 100% 100%, 50px 50px, 50px 50px;
    pointer-events: none;
    z-index: -1;
}
.container {
    background: linear-gradient(145deg, #0d0d12, #1a1a2e);
    border: 2px solid #00ffff;
    border-radius: 16px;
    padding: 40px;
    box-shadow: 0 0 30px rgba(0, 255, 255, 0.3), 0 0 60px rgba(0, 255, 255, 0.1);
    max-width: 800px;
    width: 100%;
}
header { text-align: center; margin-bottom: 30px; }
h1 {
    color: #00ffff;
    font-size: 2.5rem;
    font-weight: 700;
    text-shadow: 0 0 10px #00ffff, 0 0 20px #00ffff40;
}
main { padding: 20px 0; }
p { color: #88ffff; line-height: 1.8; letter-spacing: 1px; }
footer {
    margin-top: 40px;
    text-align: center;
    color: #00ffff80;
    font-size: 0.8rem;
    letter-spacing: 2px;
}`;
    }

    generateGenericJS(name) {
        return `// ${name} - Generated by Vigthoria AI
console.log('${name} initialized!');

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded and ready');
});`;
    }

    generateReadme(name, description) {
        return `# ${name}

${description}

## About

This project was generated by **Vigthoria AI** using the BUILD mode.

## Getting Started

1. Open \`index.html\` in your browser
2. Or use a local development server

## Features

- Modern, responsive design
- Clean code structure
- Ready for customization

## License

MIT License

---

*Generated with ❤️ by Vigthoria AI*`;
    }

    async executeCreateProject(projectStructure, workspacePath) {
        const createdFiles = [];

        for (const file of projectStructure) {
            try {
                const fullPath = path.join(workspacePath, file.path);
                const dir = path.dirname(fullPath);

                // Create directory if it doesn't exist
                if (!fs.existsSync(dir)) {
                    fs.mkdirSync(dir, { recursive: true });
                    console.log(`📁 Created directory: ${dir}`);
                }

                // Write file
                fs.writeFileSync(fullPath, file.content);
                console.log(`📄 Created file: ${fullPath}`);
                createdFiles.push(file.path);
            } catch (error) {
                console.error(`❌ Error creating ${file.path}:`, error.message);
            }
        }

        return createdFiles;
    }

    formatBuildResponse(buildRequest, projectStructure, createdFiles, workspacePath) {
        const projectPath = path.join(workspacePath, buildRequest.name);
        let response = `## 🔨 BUILD Mode - Project Created!\n\n`;
        response += `**Project:** ${buildRequest.name}\n`;
        response += `**Type:** ${buildRequest.type}\n`;
        response += `**Location:** \`${projectPath}\`\n\n`;
        response += `### 📁 Project Structure:\n\n`;
        
        // Find the main HTML file for preview
        let mainHtmlFile = null;
        
        createdFiles.forEach(file => {
            const icon = file.endsWith('.html') ? '🌐' :
                        file.endsWith('.css') ? '🎨' :
                        file.endsWith('.js') ? '⚙️' :
                        file.endsWith('.md') ? '📖' : '📄';
            response += `- ${icon} \`${file}\`\n`;
            
            // Track HTML files for preview
            if (file.endsWith('.html') && !mainHtmlFile) {
                mainHtmlFile = file;
            }
        });

        response += `\n### 🚀 Next Steps:\n\n`;
        response += `1. **Open** the project files in the explorer\n`;
        response += `2. **Run** with Live Server or open \`index.html\` in browser\n`;
        response += `3. **Customize** the code to your needs\n`;
        
        // Add preview section if HTML file was created
        if (mainHtmlFile) {
            response += `\n### 🔍 Preview Your Project:\n\n`;
            response += `Your project is now ready to preview!\n`;
            
            // Open preview automatically
            this.openProjectPreview(path.join(workspacePath, mainHtmlFile), workspacePath);
        }
        
        response += `\n---\n✅ **Project ready!** ${createdFiles.length} files created.`;

        return response;
    }

    // Add stub methods for other project types
    generateReactStructure(buildRequest) { return this.generateHTMLStructure(buildRequest); }
    generateNodeStructure(buildRequest) { return this.generateHTMLStructure(buildRequest); }
    generatePythonStructure(buildRequest) { return this.generateHTMLStructure(buildRequest); }
    generateTypeScriptStructure(buildRequest) { return this.generateHTMLStructure(buildRequest); }
    generateVueStructure(buildRequest) { return this.generateHTMLStructure(buildRequest); }
    generateNextJSStructure(buildRequest) { return this.generateHTMLStructure(buildRequest); }
}

module.exports = BuildMode;
