File size: 34,385 Bytes
f57ab04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Full-Stack App Builder</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ext-language_tools.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-gradient: linear-gradient(to right, #3b82f6, #8b5cf6);
        }
        
        .dark {
            --primary-gradient: linear-gradient(to right, #2563eb, #7c3aed);
        }
        
        .typing-animation::after {
            content: '|';
            animation: blink 1s infinite;
        }
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0; }
        }
        .file-tab.active {
            border-bottom: 2px solid #3b82f6;
            color: #3b82f6;
        }
        .code-editor {
            height: calc(100vh - 200px);
        }
        .chat-container {
            height: calc(100vh - 180px);
            overflow-y: auto;
            scroll-behavior: smooth;
        }
        .chat-container::-webkit-scrollbar {
            width: 6px;
        }
        .chat-container::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .chat-container::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 3px;
        }
        .chat-container::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
        .preview-container {
            height: calc(100vh - 60px);
        }
    </style>
</head>
<body class="bg-gray-100 font-sans">
    <div class="flex h-screen overflow-hidden bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-900">
        <!-- Left Sidebar - App Creator -->
        <div class="sidebar bg-white/80 dark:bg-gray-800/80 backdrop-blur-lg w-full shadow-lg flex flex-col z-10">
            <div class="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-tr-xl">
                <h1 class="text-xl font-bold">AI Lab</h1>
            </div>
            
            <div class="sidebar-content flex-1 flex flex-col">
                <!-- App Creator -->
                <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                    <div class="mb-3">
                        <label class="block text-sm font-medium mb-1 dark:text-gray-300">App Name</label>
                        <input id="appName" class="w-full p-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" placeholder="My Awesome AI App">
                    </div>
                    
                    <div class="mb-3">
                        <label class="block text-sm font-medium mb-1 dark:text-gray-300">App Type</label>
                        <div class="grid grid-cols-3 gap-2">
                            <button data-type="chatbot" class="app-type-btn p-2 rounded-lg border flex flex-col items-center transition-all hover:bg-blue-50 dark:hover:bg-gray-700 hover:scale-105 active:scale-95">
                                <i class="fas fa-comments text-blue-500 mb-1"></i>
                                <span class="text-xs">Chatbot</span>
                            </button>
                            <button data-type="image" class="app-type-btn p-2 rounded-lg border flex flex-col items-center transition-all hover:bg-blue-50 dark:hover:bg-gray-700 hover:scale-105 active:scale-95">
                                <i class="fas fa-image text-purple-500 mb-1"></i>
                                <span class="text-xs">Image</span>
                            </button>
                            <button data-type="video" class="app-type-btn p-2 rounded-lg border flex flex-col items-center transition-all hover:bg-blue-50 dark:hover:bg-gray-700 hover:scale-105 active:scale-95">
                                <i class="fas fa-video text-green-500 mb-1"></i>
                                <span class="text-xs">Video</span>
                            </button>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="block text-sm font-medium mb-1 dark:text-gray-300">Prompt</label>
                        <textarea id="appPrompt" class="w-full p-2 border rounded-lg h-24 dark:bg-gray-700 dark:border-gray-600" placeholder="Describe how your AI app should behave..."></textarea>
                    </div>
                    
                    <button id="createAppBtn" class="w-full bg-gradient-to-r from-blue-500 to-purple-600 text-white py-2 rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all flex items-center justify-center">
                        <i class="fas fa-plus mr-2"></i> Create App
                    </button>
                </div>
                
                <!-- Editor AI (hidden by default) -->
                <div id="editorAI" class="flex-1 flex flex-col hidden">
                    <div class="p-3 bg-gray-50/50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-700 font-medium flex items-center">
                        <div class="w-6 h-6 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center text-white mr-2">
                            <i class="fas fa-robot text-xs"></i>
                        </div>
                        <span>Editor AI</span>
                    </div>
                    
                    <div id="chatMessages" class="chat-container overflow-y-auto p-4 flex-1 space-y-4"></div>
                    
                    <div class="p-4 border-t border-gray-200 dark:border-gray-700">
                        <div class="flex items-center">
                            <input id="userMessage" type="text" class="flex-1 p-2 border rounded-l-lg dark:bg-gray-700 dark:border-gray-600" placeholder="Ask the Editor to modify your app...">
                            <button id="sendMessageBtn" class="bg-gradient-to-r from-blue-500 to-purple-600 text-white p-2 px-4 rounded-r-lg hover:from-blue-600 hover:to-purple-700 transition-all">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
    </div>

    <script>
        // Configuration
        const API_KEY = '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';
        const EDITOR_MODEL = 'deepseek/deepseek-chat-v3-0324:free';
        const APP_MODELS = {
            chatbot: 'mistralai/mistral-7b-instruct:free',
            image: 'stability-ai/sdxl:free',
            video: 'open-sora/open-sora:free'
        };
        
        // DOM Elements
        const appDescription = document.getElementById('appDescription');
        const generateBtn = document.getElementById('generateBtn');
        const chatMessages = document.getElementById('chatMessages');
        const userMessage = document.getElementById('userMessage');
        const sendMessageBtn = document.getElementById('sendMessageBtn');
        const previewTab = document.getElementById('previewTab');
        const codeTab = document.getElementById('codeTab');
        const previewPane = document.getElementById('previewPane');
        const codePane = document.getElementById('codePane');
        const fileTabs = document.getElementById('fileTabs');
        const editor = document.getElementById('editor');
        const appPreview = document.getElementById('appPreview');
        const downloadBtn = document.getElementById('downloadBtn');
        const statusMessage = document.getElementById('statusMessage');
        const fileInfo = document.getElementById('fileInfo');
        const consoleOutput = document.getElementById('consoleOutput');
        // State
        let currentFiles = {};
        let activeFile = null;
        let aceEditor = null;
        let isGenerating = false;
        let chatHistory = [];
        let currentAppType = null;
        
        // Initialize
        function init() {
            setupEventListeners();
            initializeAceEditor();
            // Initialize with empty chat - first message will be shown after app creation
        }
        
        function setupEventListeners() {
            // Theme toggle
            document.getElementById('themeToggle').addEventListener('click', () => {
                document.documentElement.classList.toggle('dark');
                localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
            });
            
            // App type selection
            document.querySelectorAll('.app-type-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    // Remove selection from all buttons
                    document.querySelectorAll('.app-type-btn').forEach(b => {
                        b.classList.remove('border-blue-500', 'bg-blue-50/50', 'ring-2', 'ring-blue-400');
                        b.querySelector('i').classList.remove('animate-pulse');
                    });
                    
                    // Add selection to clicked button
                    this.classList.add('border-blue-500', 'bg-blue-50/50', 'ring-2', 'ring-blue-400');
                    const icon = this.querySelector('i');
                    icon.classList.add('animate-pulse');
                    setTimeout(() => icon.classList.remove('animate-pulse'), 1000);
                    
                    currentAppType = this.dataset.type;
                });
            });
            
            document.getElementById('createAppBtn').addEventListener('click', createApp);
            sendMessageBtn.addEventListener('click', sendUserMessage);
            userMessage.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') sendUserMessage();
            });
            
            previewTab.addEventListener('click', () => {
                previewTab.classList.add('active');
                codeTab.classList.remove('active');
                previewPane.classList.remove('hidden');
                codePane.classList.add('hidden');
                consoleOutput.classList.add('hidden');
            });
            
            codeTab.addEventListener('click', () => {
                codeTab.classList.add('active');
                previewTab.classList.remove('active');
                previewPane.classList.add('hidden');
                codePane.classList.remove('hidden');
                consoleOutput.classList.remove('hidden');
            });
            
            downloadBtn.addEventListener('click', downloadProject);
        }
        
        function initializeAceEditor() {
            aceEditor = ace.edit('editor');
            aceEditor.setTheme('ace/theme/monokai');
            aceEditor.session.setMode('ace/mode/javascript');
            aceEditor.setOptions({
                enableBasicAutocompletion: true,
                enableLiveAutocompletion: true,
                fontSize: '14px',
                tabSize: 2
            });
            
            aceEditor.session.on('change', () => {
                if (activeFile) {
                    currentFiles[activeFile].content = aceEditor.getValue();
                    updatePreview();
                }
            });
        }
        
        async function createApp() {
            const appName = document.getElementById('appName').value.trim();
            const appPrompt = document.getElementById('appPrompt').value.trim();
            const appType = currentAppType;
            
            if (!appName || !appPrompt || !appType) {
                addSystemMessage("Please fill in all fields and select an app type.");
                return;
            }

            const createBtn = document.getElementById('createAppBtn');
            createBtn.disabled = true;
            createBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Creating App...';

            try {
                const prompt = `Create a complete ${appType} application called "${appName}" based on the following requirements: ${appPrompt}.
                The application should be a full-stack web app with proper frontend and backend structure.
                Provide all necessary files in a JSON format where each key is the file path and value is the file content.
                Include HTML, CSS, JavaScript, and any other required files.
                Make sure the code is well-structured, commented, and production-ready.`;

                const response = await queryAI(prompt, EDITOR_MODEL);
                
                // Try to parse the JSON response
                try {
                    const jsonStart = response.indexOf('{');
                    const jsonEnd = response.lastIndexOf('}') + 1;
                    const jsonStr = response.slice(jsonStart, jsonEnd);
                    const generatedFiles = JSON.parse(jsonStr);

                    if (typeof generatedFiles !== 'object' || generatedFiles === null) {
                        throw new Error("Invalid response format");
                    }

                    // Store the generated files
                    currentFiles = generatedFiles;
                    
                    // Create basic files if they weren't generated
                    if (!currentFiles['index.html']) {
                        currentFiles['index.html'] = getBaseHTML(appName);
                    }
                    if (!currentFiles['style.css']) {
                        currentFiles['style.css'] = getBaseCSS();
                    }
                    if (!currentFiles['app.js']) {
                        currentFiles['app.js'] = getBaseJS(appType, appPrompt);
                    }

                    // Update UI
                    updateFileTabs();
                    setActiveFile('index.html');
                    updatePreview();
                    
                    // Show the Editor AI section
                    document.getElementById('editorAI').classList.remove('hidden');
                    addSystemMessage(`App "${appName}" created successfully! You can now modify it using the Editor AI.`);

                } catch (e) {
                    console.error("Error parsing AI response:", e);
                    addSystemMessage("The app was created, but we couldn't parse the full response. A basic structure has been created.");
                    
                    // Fallback to basic files
                    currentFiles = {
                        'index.html': getBaseHTML(appName),
                        'style.css': getBaseCSS(),
                        'app.js': getBaseJS(appType, appPrompt)
                    };
                    
                    updateFileTabs();
                    setActiveFile('index.html');
                    updatePreview();
                    document.getElementById('editorAI').classList.remove('hidden');
                }

            } catch (error) {
                console.error("Error creating app:", error);
                addSystemMessage("Sorry, there was an error creating your app. Please try again.");
            } finally {
                createBtn.disabled = false;
                createBtn.innerHTML = '<i class="fas fa-plus mr-2"></i> Create App';
            }
        }

        function getBaseHTML(appName) {
            return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${appName}</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="app"></div>
    <script src="app.js"></script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=JayantSharma1/ai-lab" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>`;
        }

        function getBaseCSS() {
            return `body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f5f5f5;
}

#app {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}`;
        }

        function getBaseJS(appType, prompt) {
            let jsContent = `// ${appType} app - ${prompt}\n\n`;
            
            if (appType === 'chatbot') {
                jsContent += `document.getElementById('app').innerHTML = \`
                    <div class="chat-container">
                        <h1>Chatbot App</h1>
                        <div id="chat-messages"></div>
                        <input type="text" id="user-input" placeholder="Type your message...">
                        <button id="send-btn">Send</button>
                    </div>
                \`;`;
            } else if (appType === 'image') {
                jsContent += `document.getElementById('app').innerHTML = \`
                    <div class="image-generator">
                        <h1>Image Generator</h1>
                        <div id="image-result"></div>
                        <input type="text" id="prompt-input" placeholder="Describe the image you want...">
                        <button id="generate-btn">Generate</button>
                    </div>
                \`;`;
            } else if (appType === 'video') {
                jsContent += `document.getElementById('app').innerHTML = \`
                    <div class="video-generator">
                        <h1>Video Generator</h1>
                        <div id="video-result"></div>
                        <input type="text" id="prompt-input" placeholder="Describe the video you want...">
                        <button id="generate-btn">Generate</button>
                    </div>
                \`;`;
            }
            
            return jsContent;
        }
            const description = appDescription.value.trim();
            if (!description) {
                addSystemMessage("Please describe the app you want to build.");
                return;
            }
            
            if (isGenerating) {
                addSystemMessage("I'm already working on your request. Please wait...");
                return;
            }
            
            isGenerating = true;
            generateBtn.disabled = true;
            generateBtn.textContent = "Generating...";
            
            addSystemMessage("Starting to generate your app: " + description);
            
            try {
                // First, get the app structure
                const structurePrompt = `I want to build this app: ${description}. 
                Please generate a complete file structure for a full-stack application. 
                Include all necessary files for frontend (HTML, CSS, JS, React, etc.), 
                backend (Node.js, Express, etc.), and any other required files. 
                Respond with a JSON object where keys are file paths and values are 
                brief descriptions of what each file should contain.`;
                
                const structureResponse = await queryAI(structurePrompt);
                const fileStructure = parseFileStructure(structureResponse);
                
                // Then generate each file
                for (const [filePath, description] of Object.entries(fileStructure)) {
                    await generateFile(filePath, description, description);
                }
                
                // Set the first file as active
                const firstFile = Object.keys(currentFiles)[0];
                if (firstFile) {
                    setActiveFile(firstFile);
                }
                
                updatePreview();
                addSystemMessage("App generation complete! You can now preview your app and modify the code as needed.");
                
            } catch (error) {
                console.error("Error generating app:", error);
                addSystemMessage("Sorry, there was an error generating your app. Please try again.");
            } finally {
                isGenerating = false;
                generateBtn.disabled = false;
                generateBtn.textContent = "Generate App";
            }
        }
        
        function parseFileStructure(response) {
            try {
                // Try to find JSON in the response
                const jsonStart = response.indexOf('{');
                const jsonEnd = response.lastIndexOf('}') + 1;
                const jsonStr = response.slice(jsonStart, jsonEnd);
                
                const structure = JSON.parse(jsonStr);
                
                // Validate structure
                if (typeof structure !== 'object' || structure === null) {
                    throw new Error("Invalid structure format");
                }
                
                return structure;
            } catch (e) {
                console.error("Error parsing file structure:", e);
                
                // Fallback: create a basic structure
                return {
                    "package.json": "Node.js package configuration",
                    "server.js": "Express server entry point",
                    "client/index.html": "Frontend HTML file",
                    "client/styles.css": "Frontend styles",
                    "client/app.js": "Frontend JavaScript",
                    "README.md": "Project documentation"
                };
            }
        }
        
        async function generateFile(filePath, description, context) {
            showFileGenerationStatus(filePath);
            
            const prompt = `Based on this app description: "${appDescription.value.trim()}" 
            and this file context: "${context}", please generate complete code for the file 
            "${filePath}" which should contain: "${description}". 
            Respond with only the code (no explanations or markdown formatting) 
            that should be in this file.`;
            
            const code = await queryAI(prompt);
            
            // Store the file
            currentFiles[filePath] = {
                path: filePath,
                content: code,
                description: description
            };
            
            // Add file tab
            addFileTab(filePath);
            
            updateStatusMessage(`Generated ${filePath}`);
        }
        
        function showFileGenerationStatus(filePath) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'bg-blue-50 p-3 rounded-md text-sm';
            
            const typingDiv = document.createElement('div');
            typingDiv.className = 'typing-animation text-blue-600';
            typingDiv.textContent = `Generating ${filePath}...`;
            
            messageDiv.appendChild(typingDiv);
            chatMessages.appendChild(messageDiv);
            // Smooth scroll to bottom
            chatMessages.scrollTo({
                top: chatMessages.scrollHeight,
                behavior: 'smooth'
            });
        }
        
        function addFileTab(filePath) {
            // Check if tab already exists
            if (document.querySelector(`[data-file="${filePath}"]`)) {
                return;
            }
            
            const fileName = filePath.split('/').pop();
            const tab = document.createElement('button');
            tab.className = 'px-4 py-2 font-medium border-r border-gray-200 text-sm flex items-center';
            tab.dataset.file = filePath;
            tab.innerHTML = `
                <i class="fas fa-file-code mr-2 text-gray-500"></i>
                ${fileName}
                <button class="ml-2 text-gray-400 hover:text-gray-600 close-tab">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            tab.addEventListener('click', () => setActiveFile(filePath));
            
            const closeBtn = tab.querySelector('.close-tab');
            closeBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                closeFileTab(filePath);
            });
            
            fileTabs.appendChild(tab);
        }
        
        function setActiveFile(filePath) {
            if (!currentFiles[filePath]) return;
            
            // Update UI
            document.querySelectorAll('[data-file]').forEach(tab => {
                tab.classList.remove('active');
            });
            
            const activeTab = document.querySelector(`[data-file="${filePath}"]`);
            if (activeTab) {
                activeTab.classList.add('active');
            }
            
            // Set editor content
            aceEditor.setValue(currentFiles[filePath].content);
            
            // Set mode based on file extension
            const mode = getEditorMode(filePath);
            aceEditor.session.setMode(`ace/mode/${mode}`);
            
            // Update file info
            fileInfo.textContent = filePath;
            
            activeFile = filePath;
        }
        
        function getEditorMode(filePath) {
            const extension = filePath.split('.').pop().toLowerCase();
            
            switch(extension) {
                case 'js': return 'javascript';
                case 'jsx': return 'jsx';
                case 'ts': return 'typescript';
                case 'tsx': return 'tsx';
                case 'html': return 'html';
                case 'css': return 'css';
                case 'scss': return 'scss';
                case 'json': return 'json';
                case 'md': return 'markdown';
                case 'py': return 'python';
                case 'java': return 'java';
                case 'php': return 'php';
                case 'rb': return 'ruby';
                case 'go': return 'golang';
                case 'sh': return 'sh';
                default: return 'text';
            }
        }
        
        function closeFileTab(filePath) {
            // Remove from UI
            const tab = document.querySelector(`[data-file="${filePath}"]`);
            if (tab) tab.remove();
            
            // Remove from currentFiles
            delete currentFiles[filePath];
            
            // If this was the active file, set a new active file
            if (activeFile === filePath) {
                const remainingFiles = Object.keys(currentFiles);
                if (remainingFiles.length > 0) {
                    setActiveFile(remainingFiles[0]);
                } else {
                    activeFile = null;
                    aceEditor.setValue('');
                    fileInfo.textContent = '';
                }
            }
        }
        
        function updatePreview() {
            if (!activeFile) return;
            
            // For HTML files, show directly
            if (activeFile.endsWith('.html')) {
                appPreview.srcdoc = currentFiles[activeFile].content;
            }
            // For other files, we'd need a more sophisticated preview system
            // This is a simplified version
        }
        
        async function sendUserMessage() {
            const message = userMessage.value.trim();
            if (!message) return;
            
            addUserMessage(message);
            userMessage.value = '';
            
            try {
                const response = await queryAI(message);
                addSystemMessage(response);
                
                // Check if the AI is trying to modify or create files
                if (response.includes('I\'ll create') || response.includes('Here\'s the code for')) {
                    // Extract file paths and code from the response
                    // This would need more sophisticated parsing in a real implementation
                    const fileMatches = response.match(/```(?:[a-z]+\n)?([^\s]+)\n([\s\S]*?)```/g);
                    
                    if (fileMatches) {
                        fileMatches.forEach(match => {
                            const lines = match.split('\n');
                            const filePath = lines[1].trim();
                            const code = lines.slice(2, -1).join('\n');
                            
                            if (filePath && code) {
                                // Store or update the file
                                currentFiles[filePath] = {
                                    path: filePath,
                                    content: code,
                                    description: `Modified by user request: ${message}`
                                };
                                
                                addFileTab(filePath);
                                updateStatusMessage(`Updated ${filePath} based on your request`);
                            }
                        });
                    }
                }
            } catch (error) {
                console.error("Error processing user message:", error);
                addSystemMessage("Sorry, I encountered an error processing your request. Please try again.");
            }
        }
        
        async function queryAI(prompt, model = EDITOR_MODEL) {
            // Add to chat history
            chatHistory.push({ role: 'user', content: prompt });
            
            const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${API_KEY}`,
                    'Content-Type': 'application/json',
                    'HTTP-Referer': window.location.href,
                    'X-Title': 'AI App Builder'
                },
                body: JSON.stringify({
                    model: model,
                    messages: chatHistory,
                    temperature: 0.7
                })
            });
            
            if (!response.ok) {
                throw new Error(`API request failed with status ${response.status}`);
            }
            
            const data = await response.json();
            const aiResponse = data.choices[0].message.content;
            
            // Add to chat history
            chatHistory.push({ role: 'assistant', content: aiResponse });
            
            return aiResponse;
        }
        
        function addSystemMessage(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'flex';
            
            messageDiv.innerHTML = `
                <div class="flex-shrink-0 mr-3">
                    <div class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center">
                        <i class="fas fa-robot"></i>
                    </div>
                </div>
                <div class="bg-blue-50 p-3 rounded-md text-sm flex-1">
                    ${marked.parse(message)}
                </div>
            `;
            
            chatMessages.appendChild(messageDiv);
            // Smooth scroll to bottom
            chatMessages.scrollTo({
                top: chatMessages.scrollHeight,
                behavior: 'smooth'
            });
        }
        
        function addUserMessage(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'flex justify-end';
            
            messageDiv.innerHTML = `
                <div class="bg-gray-100 p-3 rounded-md text-sm max-w-[80%]">
                    ${message}
                </div>
                <div class="flex-shrink-0 ml-3">
                    <div class="w-8 h-8 rounded-full bg-gray-300 text-gray-600 flex items-center justify-center">
                        <i class="fas fa-user"></i>
                    </div>
                </div>
            `;
            
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        function updateStatusMessage(message) {
            statusMessage.textContent = message;
            setTimeout(() => {
                statusMessage.textContent = '';
            }, 3000);
        }
        
        function downloadProject() {
            if (Object.keys(currentFiles).length === 0) {
                addSystemMessage("No files to download. Please generate an app first.");
                return;
            }
            
            // In a real implementation, this would create a zip file with all files
            // For this demo, we'll just download the active file
            if (activeFile) {
                const blob = new Blob([currentFiles[activeFile].content], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = activeFile.split('/').pop();
                a.click();
                
                URL.revokeObjectURL(url);
                addSystemMessage(`Downloaded ${activeFile}`);
            }
        }
        
        // Initialize the app
        init();
    </script>
</body>
</html>