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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
let editors = {};
let currentTab = 0;
let tabs = [];
let modules = {};
let currentTheme = 'dark';

// Initialize modules
const moduleData = {
    'auth': {
        name: 'Authentication Module',
        description: 'Handles user authentication, sessions, and security',
        version: '2.1.4',
        language: 'php',
        content: `<?php
namespace App\\Modules\\Auth;

class AuthController {
    private $userService;
    
    public function __construct() {
        $this->userService = new UserService();
    }
    
    public function login($credentials) {
        if ($this->validateCredentials($credentials)) {
            $user = $this->userService->authenticate($credentials);
            if ($user) {
                return $this->createSession($user);
            }
        }
        throw new AuthenticationException("Invalid credentials");
    }
    
    private function validateCredentials($credentials) {
        return isset($credentials['email']) && isset($credentials['password']);
    }
    
    private function createSession($user) {
        $token = JWT::encode([
            'user_id' => $user->id,
            'exp' => time() + 3600
        ], $_ENV['JWT_SECRET']);
        
        return [
            'token' => $token,
            'user' => $user->toArray()
        ];
    }
}`
    },
    'api': {
        name: 'API Module',
        description: 'RESTful API endpoints and middleware',
        version: '1.5.2',
        language: 'javascript',
        content: `const express = require('express');
const router = express.Router();
const { authenticate, authorize } = require('../middleware/auth');

// Apply authentication middleware to all routes
router.use(authenticate);

// User endpoints
router.get('/users', authorize('admin'), async (req, res) => {
    try {
        const users = await User.find().select('-password');
        res.json({
            success: true,
            data: users,
            count: users.length
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

router.post('/users', authorize('admin'), async (req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).json({
            success: true,
            data: user
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
});

module.exports = router;`
    },
    'frontend': {
        name: 'Frontend Module',
        description: 'React components and UI elements',
        version: '3.0.1',
        language: 'htmlmixed',
        content: `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <style>
        .card-hover {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card-hover:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }
    </style>
</head>
<body class="bg-gray-50">
    <nav class="bg-white shadow-lg sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <h1 class="text-xl font-bold text-gray-800">Dashboard</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                        New Project
                    </button>
                </div>
            </div>
        </div>
    </nav>
    
    <main class="max-w-7xl mx-auto px-4 py-8">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div class="card-hover bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold mb-2">Analytics</h3>
                <p class="text-gray-600">View detailed analytics and reports</p>
            </div>
            <div class="card-hover bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold mb-2">Users</h3>
                <p class="text-gray-600">Manage user accounts and permissions</p>
            </div>
            <div class="card-hover bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold mb-2">Settings</h3>
                <p class="text-gray-600">Configure application settings</p>
            </div>
        </div>
    </main>
</body>
</html>`
    }
};

// Version history storage
const versionHistory = {
    'auth': [
        { version: '2.1.4', date: '2024-01-15', changes: 'Fixed session timeout issue' },
        { version: '2.1.3', date: '2024-01-10', changes: 'Improved password hashing' },
        { version: '2.1.2', date: '2024-01-05', changes: 'Added multi-factor authentication' }
    ],
    'api': [
        { version: '1.5.2', date: '2024-01-14', changes: 'Optimized database queries' },
        { version: '1.5.1', date: '2024-01-08', changes: 'Fixed CORS issues' },
        { version: '1.5.0', date: '2024-01-01', changes: 'Added rate limiting' }
    ],
    'frontend': [
        { version: '3.0.1', date: '2024-01-16', changes: 'Fixed responsive design bugs' },
        { version: '3.0.0', date: '2024-01-01', changes: 'Complete UI redesign with Tailwind' }
    ]
};

// Initialize application
document.addEventListener('DOMContentLoaded', function() {
    initializeModules();
    createDefaultTabs();
    renderModuleList();
    
    // Set initial theme
    document.documentElement.setAttribute('data-theme', currentTheme);
});

function initializeModules() {
    for (const [key, module] of Object.entries(moduleData)) {
        modules[key] = { ...module, id: key };
    }
}

function createDefaultTabs() {
    addTab('auth', 'auth.php');
    addTab('api', 'api.js');
    addTab('frontend', 'index.html');
}

function addTab(moduleId, filename) {
    const tabId = `tab-${Date.now()}`;
    const module = modules[moduleId];
    
    if (!module) return;
    
    tabs.push({
        id: tabId,
        moduleId: moduleId,
        filename: filename,
        module: module
    });
    
    // Create tab UI
    const tabContainer = document.getElementById('tabContainer');
    const tabElement = document.createElement('div');
    tabElement.className = `tab-item flex items-center gap-2 px-4 py-3 bg-gray-700 hover:bg-gray-600 cursor-pointer transition-colors border-r border-gray-600 ${tabs.length === 1 ? 'tab-active' : ''}`;
    tabElement.id = tabId;
    tabElement.onclick = () => switchTab(tabs.length - 1);
    
    const extension = filename.split('.').pop().toLowerCase();
    const iconMap = {
        'php': '<i data-feather="code" class="w-4 h-4 text-purple-400"></i>',
        'js': '<i data-feather="git-branch" class="w-4 h-4 text-yellow-400"></i>',
        'html': '<i data-feather="globe" class="w-4 h-4 text-orange-400"></i>',
        'css': '<i data-feather="droplet" class="w-4 h-4 text-blue-400"></i>'
    };
    
    tabElement.innerHTML = `
        ${iconMap[extension] || '<i data-feather="file" class="w-4 h-4"></i>'}
        <span class="text-sm">${filename}</span>
        <button onclick="event.stopPropagation(); closeTab('${tabId}')" class="ml-2 hover:bg-gray-800 rounded p-1">
            <i data-feather="x" class="w-3 h-3"></i>
        </button>
    `;
    
    tabContainer.appendChild(tabElement);
    
    // Create editor
    createEditor(tabId, module.content, module.language);
    
    // Switch to new tab
    switchTab(tabs.length - 1);
    feather.replace();
}

function createEditor(tabId, content, mode) {
    const container = document.getElementById('editorContainer');
    const editorDiv = document.createElement('div');
    editorDiv.id = `editor-${tabId}`;
    editorDiv.className = 'h-full hidden';
    editorDiv.innerHTML = `<textarea id="textarea-${tabId}"></textarea>`;
    container.appendChild(editorDiv);
    
    const editor = CodeMirror.fromTextArea(document.getElementById(`textarea-${tabId}`), {
        value: content,
        mode: mode,
        theme: currentTheme === 'dark' ? 'monokai' : 'default',
        lineNumbers: true,
        lineWrapping: true,
        autoCloseBrackets: true,
        matchBrackets: true,
        indentUnit: 4,
        tabSize: 4,
        indentWithTabs: false
    });
    
    editor.setValue(content);
    
    // Update cursor position
    editor.on('cursorActivity', function() {
        const cursor = editor.getCursor();
        document.getElementById('cursorPosition').textContent = `Ln ${cursor.line + 1}, Col ${cursor.ch + 1}`;
    });
    
    // Update file info
    editor.on('change', function() {
        const tab = tabs.find(t => t.id === tabId);
        if (tab) {
            document.getElementById('fileInfo').textContent = `${tab.filename} • Modified`;
        }
    });
    
    editors[tabId] = editor;
}

function switchTab(index) {
    // Hide all editors
    tabs.forEach(tab => {
        const editorDiv = document.getElementById(`editor-${tab.id}`);
        if (editorDiv) editorDiv.classList.add('hidden');
        
        const tabElement = document.getElementById(tab.id);
        if (tabElement) tabElement.classList.remove('tab-active');
    });
    
    // Show selected editor
    const selectedTab = tabs[index];
    const editorDiv = document.getElementById(`editor-${selectedTab.id}`);
    if (editorDiv) {
        editorDiv.classList.remove('hidden');
        // Refresh editor to fix display issues
        setTimeout(() => {
            editors[selectedTab.id].refresh();
        }, 10);
    }
    
    const tabElement = document.getElementById(selectedTab.id);
    if (tabElement) tabElement.classList.add('tab-active');
    
    currentTab = index;
    
    // Update status bar
    document.getElementById('fileInfo').textContent = selectedTab.filename;
    document.getElementById('language').textContent = selectedTab.module.language.toUpperCase();
    document.getElementById('gitBranch').textContent = selectedTab.moduleId;
}

function closeTab(tabId) {
    const index = tabs.findIndex(t => t.id === tabId);
    if (index === -1) return;
    
    // Remove tab
    tabs.splice(index, 1);
    
    // Remove UI elements
    const tabElement = document.getElementById(tabId);
    if (tabElement) tabElement.remove();
    
    const editorDiv = document.getElementById(`editor-${tabId}`);
    if (editorDiv) editorDiv.remove();
    
    delete editors[tabId];
    
    // Switch to another tab if available
    if (tabs.length > 0) {
        switchTab(Math.min(currentTab, tabs.length - 1));
    }
}

function addNewTab() {
    // Create a simple file selection dialog
    const moduleKeys = Object.keys(modules);
    const moduleId = moduleKeys[Math.floor(Math.random() * moduleKeys.length)];
    const module = modules[moduleId];
    const extension = module.language === 'htmlmixed' ? 'html' : module.language;
    const filename = `new-${Date.now()}.${extension}`;
    
    addTab(moduleId, filename);
}

function renderModuleList() {
    const moduleList = document.getElementById('moduleList');
    moduleList.innerHTML = '';
    
    Object.values(modules).forEach(module => {
        const moduleElement = document.createElement('div');
        moduleElement.className = 'module-item bg-gray-700 rounded-lg p-4 cursor-pointer';
        
        moduleElement.innerHTML = `
            <div class="flex items-start justify-between mb-2">
                <div class="flex-1">
                    <h3 class="font-semibold text-white flex items-center gap-2">
                        ${getModuleIcon(module.language)}
                        ${module.name}
                    </h3>
                    <p class="text-xs text-gray-400 mt-1">${module.description}</p>
                    <div class="flex items-center gap-2 mt-2">
                        <span class="text-xs bg-blue-600 text-white px-2 py-1 rounded">v${module.version}</span>
                        <span class="text-xs text-gray-400">${module.language}</span>
                    </div>
                </div>
                <div class="flex flex-col gap-1">
                    <button onclick="showVersionHistory('${module.id}')" class="action-button p-2 hover:bg-gray-600 rounded" title="Version History">
                        <i data-feather="git-branch" class="w-3 h-3"></i>
                    </button>
                    <button onclick="showDiffView('${module.id}')" class="action-button p-2 hover:bg-gray-600 rounded" title="Show Diff">
                        <i data-feather="git-merge" class="w-3 h-3"></i>
                    </button>
                    <button onclick="changeModuleVersion('${module.id}')" class="action-button p-2 hover:bg-gray-600 rounded" title="Change Version">
                        <i data-feather="refresh-cw" class="w-3 h-3"></i>
                    </button>
                </div>
            </div>
        `;
        
        moduleElement.onclick = (e) => {
            if (e.target.closest('button')) return;
            openModuleTab(module.id);
        };
        
        moduleList.appendChild(moduleElement);
    });
    
    feather.replace();
}

function getModuleIcon(language) {
    const icons = {
        'php': '<i data-feather="code" class="w-4 h-4 text-purple-400"></i>',
        'javascript': '<i data-feather="git-branch" class="w-4 h-4 text-yellow-400"></i>',
        'htmlmixed': '<i data-feather="globe" class="w-4 h-4 text-orange-400"></i>'
    };
    return icons[language] || '<i data-feather="file" class="w-4 h-4"></i>';
}

function openModuleTab(moduleId) {
    const module = modules[moduleId];
    if (!module) return;
    
    // Check if tab already exists
    const existingTab = tabs.find(t => t.moduleId === moduleId);
    if (existingTab) {
        const index = tabs.findIndex(t => t.id === existingTab.id);
        switchTab(index);
        return;
    }
    
    const extension = module.language === 'htmlmixed' ? 'html' : module.language;
    const filename = `${moduleId}.${extension}`;
    addTab(moduleId, filename);
}

function showVersionHistory(moduleId) {
    const modal = document.getElementById('versionModal');
    const versionList = document.getElementById('versionList');
    const history = versionHistory[moduleId] || [];
    
    versionList.innerHTML = history.map(v => `
        <div class="version-item bg-gray-700 rounded p-3 text-sm">
            <div class="flex justify-between items-start">
                <div>
                    <span class="font-semibold text-white">v${v.version}</span>
                    <span class="text-xs text-gray-400 ml-2">${v.date}</span>
                </div>
            </div>
            <p class="text-xs text-gray-300 mt-1">${v.changes}</p>
        </div>
    `).join('');
    
    modal.classList.remove('hidden');
    modal.dataset.moduleId = moduleId;
}

function closeVersionModal() {
    document.getElementById('versionModal').classList.add('hidden');
}

function createPatch() {
    const modal = document.getElementById('versionModal');
    const moduleId = modal.dataset.moduleId;
    
    if (moduleId) {
        alert(`Creating patch for ${modules[moduleId]?.name || 'Module'}...`);
    }
    
    closeVersionModal();
}

function showDiffView(moduleId) {
    const module = modules[moduleId];
    if (!module) return;
    
    // Create a diff view tab
    const tabId = `diff-${Date.now()}`;
    const tabContainer = document.getElementById('tabContainer');
    
    const tabElement = document.createElement('div');
    tabElement.className = 'tab-item flex items-center gap-2 px-4 py-3 bg-gray-700 hover:bg-gray-600 cursor-pointer transition-colors border-r border-gray-600';
    tabElement.id = tabId;
    
    tabElement.innerHTML = `
        <i data-feather="git-merge" class="w-4 h-4 text-green-400"></i>
        <span class="text-sm">${moduleId} - Diff</span>
        <button onclick="event.stopPropagation(); closeTab('${tabId}')" class="ml-2 hover:bg-gray-800 rounded p-1">
            <i data-feather="x" class="w-3 h-3"></i>
        </button>
    `;
    
    tabContainer.appendChild(tabElement);
    
    tabs.push({
        id: tabId,
        moduleId: moduleId,
        filename: `${moduleId} - Diff`,
        module: module,
        isDiff: true
    });
    
    // Create diff view
    const container = document.getElementById('editorContainer');
    const editorDiv = document.createElement('div');
    editorDiv.id = `editor-${tabId}`;
    editorDiv.className = 'h-full hidden';
    editorDiv.innerHTML = `
        <div class="flex h-full">
            <div class="w-1/2 h-full">
                <div class="bg-gray-700 px-4 py-2 text-sm font-semibold">Current Version</div>
                <textarea id="diff-left-${tabId}"></textarea>
            </div>
            <div class="w-1/2 h-full border-l border-gray-600">
                <div class="bg-gray-700 px-4 py-2 text-sm font-semibold">Previous Version</div>
                <textarea id="diff-right-${tabId}"></textarea>
            </div>
        </div>
    `;
    container.appendChild(editorDiv);
    
    // Initialize diff editors
    const leftEditor = CodeMirror.fromTextArea(document.getElementById(`diff-left-${tabId}`), {
        mode: module.language,
        theme: currentTheme === 'dark' ? 'monokai' : 'default',
        lineNumbers: true,
        readOnly: true
    });
    
    const rightEditor = CodeMirror.fromTextArea(document.getElementById(`diff-right-${tabId}`), {
        mode: module.language,
        theme: currentTheme === 'dark' ? 'monokai' : 'default',
        lineNumbers: true,
        readOnly: true
    });
    
    leftEditor.setValue(module.content);
    rightEditor.setValue(module.content.substring(0, Math.floor(module.content.length * 0.7)));
    
    editors[tabId] = { left: leftEditor, right: rightEditor, isDiff: true };
    
    switchTab(tabs.length - 1);
    feather.replace();
}

function changeModuleVersion(moduleId) {
    const module = modules[moduleId];
    if (!module) return;
    
    const versions = versionHistory[moduleId] || [];
    if (versions.length === 0) {
        alert('No previous versions available');
        return;
    }
    
    const newVersion = versions[0];
    module.version = newVersion.version;
    
    renderModuleList();
    alert(`Module updated to version ${newVersion.version}`);
}

function toggleTheme() {
    currentTheme = currentTheme === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', currentTheme);
    
    const themeIcon = document.querySelector('.theme-icon');
    themeIcon.setAttribute('data-feather', currentTheme === 'dark' ? 'sun' : 'moon');
    feather.replace();
    
    // Update all editor themes
    Object.values(editors).forEach(editor => {
        if (editor.isDiff) {
            if (editor.left) editor.left.setOption('theme', currentTheme === 'dark' ? 'monokai' : 'default');
            if (editor.right) editor.right.setOption('theme', currentTheme === 'dark' ? 'monokai' : 'default');
        } else {
            editor.setOption('theme', currentTheme === 'dark' ? 'monokai' : 'default');
        }
    });
}