File size: 21,957 Bytes
f625374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e5655
f625374
c6c10b8
 
 
 
 
f625374
 
 
 
30e5655
c6c10b8
 
 
30e5655
c6c10b8
f625374
 
c6c10b8
 
f625374
30e5655
f625374
c6c10b8
 
30e5655
c6c10b8
f625374
 
c6c10b8
 
f625374
30e5655
f625374
c6c10b8
 
 
30e5655
c6c10b8
 
 
 
 
 
 
 
 
 
f625374
 
c6c10b8
 
f625374
30e5655
f625374
c6c10b8
 
 
30e5655
c6c10b8
 
 
 
 
 
 
 
 
f625374
 
c6c10b8
 
 
30e5655
c6c10b8
 
 
30e5655
c6c10b8
 
f625374
 
 
30e5655
f625374
 
30e5655
 
 
 
 
 
f625374
 
30e5655
 
 
 
 
 
f625374
 
30e5655
f625374
 
30e5655
 
 
 
 
 
 
 
 
f625374
30e5655
f625374
 
30e5655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f625374
 
 
 
c6c10b8
f625374
 
 
c6c10b8
 
 
 
 
 
 
 
f625374
 
c6c10b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f625374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e5655
 
f625374
 
 
30e5655
f625374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6c10b8
f625374
 
 
 
c6c10b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f625374
 
c6c10b8
 
 
 
 
f625374
 
 
 
 
 
 
 
c6c10b8
f625374
 
 
 
 
c6c10b8
f625374
c6c10b8
 
 
 
 
 
 
f625374
c6c10b8
 
 
f625374
 
c6c10b8
 
f625374
 
c6c10b8
 
 
f625374
 
c6c10b8
 
 
f625374
 
c6c10b8
 
 
 
 
 
 
 
 
 
 
f625374
 
 
 
 
 
 
 
 
 
 
 
 
c6c10b8
 
 
 
f625374
 
 
 
c6c10b8
 
 
 
 
f625374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f56d5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// DOM Elements
const inputText = document.getElementById('input-text');
const outputText = document.getElementById('output-text');
const optimizeBtn = document.getElementById('optimize-btn');
const clearBtn = document.getElementById('clear-btn');
const exampleBtn = document.getElementById('example-btn');
const copyBtn = document.getElementById('copy-btn');
const charCount = document.getElementById('char-count');
const optimizationScore = document.getElementById('optimization-score');
const toast = document.getElementById('toast');
const toastMessage = document.getElementById('toast-message');

// Tab elements
const tabBtns = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');

// Analysis elements
const analysisContent = document.getElementById('analysis-content');
const beforeText = document.getElementById('before-text');
const afterText = document.getElementById('after-text');

// Example prompts
const examples = [
    "Make me a website for my restaurant",
    "Write a function to sort numbers",
    "Create a chatbot for customer service",
    "Generate a report about sales data",
    "Build an app to track expenses",
    "Design a landing page for my startup",
    "Write code to connect to a database",
    "Create an API endpoint for user authentication"
];
// Optimization templates and rules
const optimizationRules = {
    // Add structured sections with enhanced formatting
    addStructure: (text) => {
        const hasRole = /^role:/im.test(text.trim());
        const hasGoal = /^goal:/im.test(text.trim());
        const hasConstraints = /^constraints:/im.test(text.trim());
        const hasSteps = /^steps:/im.test(text.trim());
        const hasSuccess = /^success criteria:/im.test(text.trim());
        
        let structured = '';
        
        if (!hasRole) {
            structured += 'ROLE: AI Assistant\n';
        } else {
            const roleMatch = text.match(/^role:(.+?)(?=\n\w+:|$)/im);
            if (roleMatch) {
                structured += 'ROLE: ' + roleMatch[1].trim() + '\n';
            }
        }
        
        structured += '\n';
        
        if (!hasGoal) {
            structured += 'GOAL: Execute the specified task with absolute precision, robustness, and full adherence to the intended functionality.\n';
        } else {
            const goalMatch = text.match(/^goal:(.+?)(?=\n\w+:|$)/im);
            if (goalMatch) {
                structured += 'GOAL: ' + goalMatch[1].trim() + '\n';
            }
        }
        
        structured += '\n';
        
        if (!hasConstraints) {
            structured += 'CONSTRAINTS:\n- Operate without errors, omissions, or deviations from the defined purpose.\n- Ensure maximum reliability and performance under all expected conditions.\n- Do not introduce assumptions, interpretations, or modifications beyond the defined scope.\n';
        } else {
            const constraintsMatch = text.match(/^constraints:(.+?)(?=\n\w+:|$)/ims);
            if (constraintsMatch) {
                const constraints = constraintsMatch[1].trim().split('\n');
                structured += 'CONSTRAINTS:\n';
                constraints.forEach(line => {
                    if (line.trim()) {
                        if (!line.startsWith('-')) {
                            structured += '- ' + line.trim() + '\n';
                        } else {
                            structured += line.trim() + '\n';
                        }
                    }
                });
            }
        }
        
        structured += '\n';
        
        if (!hasSteps) {
            structured += 'STEPS:\n1. Analyze the core objective of the task as explicitly and implicitly defined.\n2. Implement the solution with complete fidelity to the intended behavior.\n3. Reinforce all components to ensure flawless, brute-force reliability.\n4. Validate output against the highest standard of functional correctness.\n5. Deliver the final result in a fully optimized, error-free state.\n';
        } else {
            const stepsMatch = text.match(/^steps:(.+?)(?=\n\w+:|$)/ims);
            if (stepsMatch) {
                const steps = stepsMatch[1].trim().split('\n');
                structured += 'STEPS:\n';
                let stepNum = 1;
                steps.forEach(line => {
                    if (line.trim()) {
                        const cleanLine = line.replace(/^\d+\.?\s*/, '').trim();
                        structured += stepNum + '. ' + cleanLine + '\n';
                        stepNum++;
                    }
                });
            }
        }
        
        structured += '\n';
        
        if (!hasSuccess) {
            structured += 'SUCCESS CRITERIA: The output must perform perfectly, consistently, and robustly according to the original intent, with no failure under expected use.';
        } else {
            const successMatch = text.match(/^success criteria:(.+?)(?=\n\w+:|$)/im);
            if (successMatch) {
                structured += 'SUCCESS CRITERIA: ' + successMatch[1].trim();
            }
        }
        
        return structured;
    },
// Convert to imperative commands with stronger action verbs
    makeImperative: (text) => {
        return text
            .replace(/I want you to/gi, 'MANDATE: GENERATE')
            .replace(/can you/gi, 'DIRECTIVE: EXECUTE')
            .replace(/please/gi, 'REQUIREMENT:')
            .replace(/I need/gi, 'SPECIFICATION: PRODUCE')
            .replace(/we should/gi, 'IMPLEMENTATION: ESTABLISH')
            .replace(/it would be good if/gi, 'MANDATORY: ENSURE')
            .replace(/\bmake\b/gi, 'CONSTRUCT')
            .replace(/\bwrite\b/gi, 'COMPOSE')
            .replace(/\bbuild\b/gi, 'ENGINEER')
            .replace(/\bcreate\b/gi, 'GENERATE')
            .replace(/\bdevelop\b/gi, 'ENGINEER')
            .replace(/\bdesign\b/gi, 'ARCHITECT')
            .replace(/\bimplement\b/gi, 'DEPLOY')
            .replace(/\bcode\b/gi, 'PROGRAM');
    },
    
    // Add technical precision with stronger terminology
    addPrecision: (text) => {
        return text
            .replace(/good/gi, 'OPTIMAL')
            .replace(/nice/gi, 'AESTHETICALLY SUPERIOR')
            .replace(/fast/gi, 'HIGH-PERFORMANCE')
            .replace(/simple/gi, 'MINIMALIST WITH CLEAN ARCHITECTURE')
            .replace(/modern/gi, 'STATE-OF-THE-ART')
            .replace(/professional/gi, 'ENTERPRISE-GRADE')
            .replace(/efficient/gi, 'RESOURCE-OPTIMIZED')
            .replace(/reliable/gi, 'FAULT-TOLERANT')
            .replace(/secure/gi, 'CYBERSECURE');
    },
    // Add comprehensive scope definition
    addScope: (text) => {
        if (!/scope|boundary|limit/i.test(text)) {
            text += '\n\nSCOPE DEFINITION:\n- IN-SCOPE: [Specify all included elements and functionalities]\n- OUT-OF-SCOPE: [Define explicitly excluded items and limitations]\n- BOUNDARIES: [Establish clear operational limits]\n- SUCCESS METRICS: [Define quantifiable performance indicators]';
        }
        return text;
    },
    
    // Add quality assurance protocols
    addQualityAssurance: (text) => {
        if (!/quality|validation|testing/i.test(text)) {
            text += '\n\nQUALITY ASSURANCE PROTOCOL:\n- VALIDATION: Verify output against all specified requirements\n- TESTING: Execute comprehensive functionality tests\n- VERIFICATION: Confirm adherence to all constraints\n- OPTIMIZATION: Ensure peak performance under all conditions';
        }
        return text;
    },
    
    // Add error handling specifications
    addErrorHandling: (text) => {
        if (!/error|exception|failure/i.test(text)) {
            text += '\n\nERROR HANDLING SPECIFICATION:\n- EXCEPTION MANAGEMENT: Implement robust error detection and recovery\n- FAILURE MODES: Define all possible failure scenarios\n- RECOVERY PROCEDURES: Establish automatic recovery protocols\n- LOGGING: Maintain detailed error logs for diagnostics';
        }
        return text;
    }
};
// Extract sections from text - Enhanced for precision
function extractSection(text, sectionType) {
    const lines = text.split('\n');
    let section = '';
    let inSection = false;
    const sectionPatterns = {
        'ROLE': /^role:/im,
        'GOAL': /^goal:/im,
        'CONSTRAINTS': /^constraints?:/im,
        'STEPS': /^steps?:/im,
        'SUCCESS CRITERIA': /^success criteria:/im
    };
    
    for (const line of lines) {
        const trimmedLine = line.trim();
        
        // Check if we're entering the target section
        if (sectionPatterns[sectionType] && sectionPatterns[sectionType].test(trimmedLine)) {
            inSection = true;
            section += line + '\n';
            continue;
        }
        
        // Check if we're entering a different section (exit current section)
        if (inSection) {
            let foundNewSection = false;
            for (const [key, pattern] of Object.entries(sectionPatterns)) {
                if (key !== sectionType && pattern.test(trimmedLine)) {
                    foundNewSection = true;
                    break;
                }
            }
            if (foundNewSection) break;
        }
        
        // Add line if we're in the target section
        if (inSection) {
            section += line + '\n';
        }
    }
    
    return section || `${sectionType}:\n${text}`;
}
// Optimize the input text
function optimizeText() {
    const input = inputText.value.trim();
    
    if (!input) {
        showToast('Please enter some text to optimize', 'error');
        return;
    }
    
    // Add loading state
    optimizeBtn.classList.add('loading');
    optimizeBtn.innerHTML = '<i data-feather="loader" class="w-5 h-5 animate-spin"></i>';
    feather.replace();
    
    setTimeout(() => {
        let optimized = input;
        // Apply optimization rules
        optimized = optimizationRules.makeImperative(optimized);
        optimized = optimizationRules.addPrecision(optimized);
        optimized = optimizationRules.addScope(optimized);
        optimized = optimizationRules.addQualityAssurance(optimized);
        optimized = optimizationRules.addErrorHandling(optimized);
        
        // Check if structure is needed
        const hasStructure = /role|goal|constraint|step|output format/i.test(optimized);
if (!hasStructure || optimized.split('\n').length < 3) {
            optimized = optimizationRules.addStructure(optimized);
        }
        
        // Clean up extra whitespace
        optimized = optimized.replace(/\n\s*\n\s*\n/g, '\n\n').trim();
        
        // Update output
        outputText.value = optimized;
        updateCharCount();
        updateOptimizationScore(input, optimized);
        updateAnalysis(input, optimized);
        
        // Remove loading state
        optimizeBtn.classList.remove('loading');
        optimizeBtn.innerHTML = '<i data-feather="zap" class="w-5 h-5 mr-2"></i>Optimize Prompt';
        feather.replace();
        
        showToast('Prompt optimized successfully!');
    }, 800);
}

// Update character count
function updateCharCount() {
    const count = outputText.value.length;
    charCount.textContent = `${count} characters`;
}
// Calculate optimization score - Enhanced for precision
function updateOptimizationScore(original, optimized) {
    const originalWords = original.split(/\s+/).length;
    const optimizedWords = optimized.split(/\s+/).length;
    
    // Check for required structure components
    const hasRole = /^role:/im.test(optimized);
    const hasGoal = /^goal:/im.test(optimized);
    const hasConstraints = /^constraints:/im.test(optimized);
    const hasSteps = /^steps:/im.test(optimized);
    const hasSuccess = /^success criteria:/im.test(optimized);
    
    const structureScore = (hasRole + hasGoal + hasConstraints + hasSteps + hasSuccess) * 20;
    
    // Check for precision keywords
    const precisionKeywords = /precision|robustness|reliability|consistently|flawless|maximum|absolute/gi;
    const precisionCount = (optimized.match(precisionKeywords) || []).length;
    const precisionScore = Math.min(20, precisionCount * 4);
    
    // Check for action-oriented language
    const actionKeywords = /execute|implement|validate|deliver|analyze|reinforce/gi;
    const actionCount = (optimized.match(actionKeywords) || []).length;
    const actionScore = Math.min(20, actionCount * 4);
    
    // Clarity and specificity bonus
    const clarityBonus = optimized.includes('no failure under expected use') ? 10 : 0;
    const specificityBonus = optimized.includes('highest standard') ? 10 : 0;
    
    const score = Math.min(100, structureScore + precisionScore + actionScore + clarityBonus + specificityBonus);
    
    let scoreColor = 'text-red-500';
    if (score >= 95) scoreColor = 'text-green-500';
    else if (score >= 85) scoreColor = 'text-green-600';
    else if (score >= 75) scoreColor = 'text-yellow-500';
    else if (score >= 65) scoreColor = 'text-orange-500';
    else if (score >= 50) scoreColor = 'text-red-600';
    
    optimizationScore.textContent = `Optimization Score: ${score}/100`;
    optimizationScore.className = `font-semibold ${scoreColor} score-update`;
    
    setTimeout(() => {
        optimizationScore.classList.remove('score-update');
    }, 500);
}
// Update analysis section - Enhanced for robustness
function updateAnalysis(original, optimized) {
    beforeText.textContent = original;
    afterText.textContent = optimized;
    
    const improvements = [];
    const structureComponents = ['Role', 'Goal', 'Constraints', 'Steps', 'Success Criteria'];
    
    // Check for structure components
    structureComponents.forEach(component => {
        const pattern = new RegExp(`^${component}:`, 'im');
        if (!pattern.test(original) && pattern.test(optimized)) {
            improvements.push(`βœ… Added ${component} section for comprehensive structure`);
        }
    });
    
    // Check for precision enhancements
    if (!/precision|robustness|reliability|absolute/gi.test(original)) {
        improvements.push('βœ… Enhanced with precision-focused language');
    }
    
    if (!/maximum|flawless|consistent/gi.test(original)) {
        improvements.push('βœ… Added reliability and consistency requirements');
    }
    
    // Check for action-oriented transformation
    if (!/execute|implement|validate|deliver/gi.test(original)) {
        improvements.push('βœ… Transformed to action-oriented directives');
    }
    
    // Check for error prevention
    if (!/without errors|no failure|no deviations/gi.test(original)) {
        improvements.push('βœ… Implemented error prevention measures');
    }
    
    // Calculate metrics
    const hasRole = /^role:/im.test(optimized);
    const hasGoal = /^goal:/im.test(optimized);
    const hasConstraints = /^constraints:/im.test(optimized);
    const hasSteps = /^steps:/im.test(optimized);
    const hasSuccess = /^success criteria:/im.test(optimized);
    const structureCount = [hasRole, hasGoal, hasConstraints, hasSteps, hasSuccess].filter(Boolean).length;
    
    const precisionCount = (optimized.match(/precision|robustness|reliability|absolute|flawless|maximum/gi) || []).length;
    const actionCount = (optimized.match(/execute|implement|validate|deliver|analyze|reinforce/gi) || []).length;
    
    const analysisHTML = `
        <div class="space-y-3">
            <div class="bg-blue-50 p-3 rounded-lg">
                <h4 class="font-semibold text-blue-800 mb-1">Key Improvements Applied:</h4>
                <ul class="text-sm space-y-1">
                    ${improvements.map(imp => `<li class="flex items-start"><span class="mr-2">β€’</span>${imp}</li>`).join('')}
                </ul>
            </div>
            <div class="bg-green-50 p-3 rounded-lg">
                <h4 class="font-semibold text-green-800 mb-1">Optimization Metrics:</h4>
                <div class="grid grid-cols-2 gap-2 text-sm">
                    <div>Original Words: <span class="font-semibold">${original.split(/\s+/).length}</span></div>
                    <div>Optimized Words: <span class="font-semibold">${optimized.split(/\s+/).length}</span></div>
                    <div>Structure Components: <span class="font-semibold">${structureCount}/5</span></div>
                    <div>Precision Keywords: <span class="font-semibold">${precisionCount}</span></div>
                    <div>Action Directives: <span class="font-semibold">${actionCount}</span></div>
                    <div>Robustness Score: <span class="font-semibold">${Math.min(100, structureCount * 20 + precisionCount * 3 + actionCount * 2)}%</span></div>
                </div>
            </div>
            <div class="bg-purple-50 p-3 rounded-lg">
                <h4 class="font-semibold text-purple-800 mb-1">Expected Impact:</h4>
                <p class="text-sm">This optimized prompt will execute with absolute precision, ensuring maximum reliability and performance under all expected conditions. The structure eliminates ambiguity, enforces error-free operation, and delivers consistent results according to the highest functional standards.</p>
            </div>
            <div class="bg-orange-50 p-3 rounded-lg">
                <h4 class="font-semibold text-orange-800 mb-1">Compliance Status:</h4>
                <p class="text-sm">βœ… All constraints defined and enforced<br>βœ… Success criteria clearly specified<br>βœ… No assumptions beyond defined scope<br>βœ… Brute-force reliability implemented</p>
            </div>
        </div>
    `;
    
    analysisContent.innerHTML = analysisHTML;
}
// Copy to clipboard
function copyToClipboard() {
    if (!outputText.value) {
        showToast('No optimized prompt to copy', 'error');
        return;
    }
    
    outputText.select();
    document.execCommand('copy');
    showToast('Optimized prompt copied to clipboard!');
}

// Clear all fields
function clearAll() {
    inputText.value = '';
    outputText.value = '';
    charCount.textContent = '0 characters';
    optimizationScore.textContent = '';
    analysisContent.innerHTML = '<p class="text-gray-500">Analysis will appear after optimization...</p>';
    beforeText.textContent = '';
    afterText.textContent = '';
    
    showToast('Fields cleared');
}

// Load random example
function loadExample() {
    const randomExample = examples[Math.floor(Math.random() * examples.length)];
    inputText.value = randomExample;
    inputText.focus();
    showToast('Example loaded - try optimizing it!');
}

// Show toast notification
function showToast(message, type = 'success') {
    toastMessage.textContent = message;
    
    // Update toast color based on type
    if (type === 'error') {
        toast.className = 'fixed bottom-8 right-8 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg transform transition-all duration-300 flex items-center';
    } else {
        toast.className = 'fixed bottom-8 right-8 bg-gray-800 text-white px-6 py-3 rounded-lg shadow-lg transform transition-all duration-300 flex items-center';
    }
    
    toast.classList.add('show');
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// Tab switching
function switchTabs() {
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const targetTab = btn.dataset.tab;
            
            // Update button states
            tabBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            // Update content visibility
            tabContents.forEach(content => {
                content.classList.add('hidden');
            });
            document.getElementById(`${targetTab}-tab`).classList.remove('hidden');
        });
    });
}

// Real-time character count
inputText.addEventListener('input', updateCharCount);
outputText.addEventListener('input', updateCharCount);

// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
    // Ctrl/Cmd + Enter to optimize
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        optimizeText();
    }
    
    // Ctrl/Cmd + Shift + C to copy
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
        e.preventDefault();
        copyToClipboard();
    }
    
    // Escape to clear
    if (e.key === 'Escape') {
        clearAll();
    }
});

// Initialize event listeners
optimizeBtn.addEventListener('click', optimizeText);
clearBtn.addEventListener('click', clearAll);
exampleBtn.addEventListener('click', loadExample);
copyBtn.addEventListener('click', copyToClipboard);

// Initialize tabs
switchTabs();
// Auto-focus on load
window.addEventListener('load', () => {
    inputText.focus();
});

// Hugging Face Bookmarklet Integration
class BookmarkletManager {
  constructor() {
    this.panel = null;
  }

  init() {
    // Check if we're on Hugging Face
    if (!window.location.href.includes('huggingface.co')) {
      return;
    }

    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => this.injectPanel());
    } else {
      this.injectPanel();
    }
  }

  injectPanel() {
    // Check if panel already exists
    if (document.querySelector('hf-panel')) {
      return;
    }

    // Create and inject panel
    this.panel = document.createElement('hf-panel');
    document.body.appendChild(this.panel);
  }

  removePanel() {
    if (this.panel) {
      this.panel.remove();
      this.panel = null;
    }
  }
}

// Expose globally
window.bookmarkletManager = new BookmarkletManager();

// Auto-initialize when page is ready
window.initHFBookmarklet = () => {
  window.bookmarkletManager.init();
};

// Run initialization if we're on Hugging Face
if (window.location.href.includes('huggingface.co')) {
  window.initHFBookmarklet();
}