File size: 27,301 Bytes
9a826b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// State Management
const AppState = {
    currentImage: null,
    currentVideo: null,
    isGenerating: false,
    history: JSON.parse(localStorage.getItem('generationHistory') || '[]'),
    settings: {
        width: 1024,
        height: 1024,
        steps: 30,
        cfgScale: 7.5,
        seed: -1,
        motionStrength: 5,
        videoDuration: 4
    }
};

// Utility Functions
const Utils = {
    generateId: () => Math.random().toString(36).substr(2, 9),
    
    async hashString(str) {
        const encoder = new TextEncoder();
        const data = encoder.encode(str);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    },

    getRandomSeed() {
        return Math.floor(Math.random() * 2147483647);
    },

    formatDate(date) {
        return new Intl.DateTimeFormat('en-US', {
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        }).format(date);
    },

    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
};

// API Simulation (Mock)
const APIService = {
    async generateImage(prompt, negativePrompt, settings) {
        // Simulate API delay
        await new Promise(resolve => setTimeout(resolve, 2000 + Math.random() * 2000));
        
        // Generate deterministic seed from prompt for consistent demo results
        const seed = settings.seed > 0 ? settings.seed : Math.abs(Utils.hashString(prompt).split('').reduce((a,b)=>a+b.charCodeAt(0),0));
        
        // Use static.photos with random category based on prompt content
        const categories = ['technology', 'abstract', 'nature', 'people', 'cityscape', 'minimal'];
        const category = categories[seed % categories.length];
        const dimensions = settings.width > settings.height ? '1200x630' : settings.width < settings.height ? '640x360' : '1024x576';
        
        return {
            id: Utils.generateId(),
            url: `http://static.photos/${category}/${dimensions}/${seed % 999}`,
            prompt: prompt,
            negativePrompt: negativePrompt,
            settings: {...settings},
            timestamp: new Date(),
            seed: seed,
            type: 'image'
        };
    },

    async generateVideo(imageUrl, prompt, settings) {
        await new Promise(resolve => setTimeout(resolve, 3000 + Math.random() * 3000));
        
        const seed = Utils.getRandomSeed();
        
        return {
            id: Utils.generateId(),
            imageUrl: imageUrl,
            videoUrl: `http://static.photos/technology/640x360/${seed % 999}`, // Simulated video thumbnail
            prompt: prompt,
            settings: {...settings},
            timestamp: new Date(),
            duration: settings.videoDuration || 4,
            type: 'video'
        };
    }
};

// UI Components Logic
const UI = {
    showLoading(element, text = 'Generating...') {
        element.innerHTML = `
            <div class="flex flex-col items-center justify-center space-y-4 p-8">
                <div class="relative w-16 h-16">
                    <div class="absolute inset-0 border-4 border-primary-500/30 rounded-full"></div>
                    <div class="absolute inset-0 border-4 border-t-primary-500 border-r-transparent border-b-transparent border-l-transparent rounded-full animate-spin"></div>
                </div>
                <p class="text-primary-400 animate-pulse font-mono text-sm">${text}</p>
                <div class="w-48 h-1 bg-slate-800 rounded-full overflow-hidden">
                    <div class="h-full bg-gradient-to-r from-primary-500 to-secondary-500 animate-[shimmer_2s_infinite]" style="width: 0%; animation: loadingProgress 3s ease-out forwards;"></div>
                </div>
            </div>
            <style>
                @keyframes loadingProgress {
                    0% { width: 0%; }
                    100% { width: 100%; }
                }
            </style>
        `;
    },

    showError(element, message) {
        element.innerHTML = `
            <div class="flex flex-col items-center justify-center space-y-3 p-8 text-red-400">
                <i data-feather="alert-circle" class="w-12 h-12"></i>
                <p class="text-center">${message}</p>
                <button onclick="this.closest('.error-container').remove()" class="px-4 py-2 bg-red-500/20 hover:bg-red-500/30 rounded-lg text-sm transition-colors">
                    Dismiss
                </button>
            </div>
        `;
        feather.replace();
    },

    createImageCard(item) {
        return `
            <div class="group relative bg-slate-900/50 rounded-xl overflow-hidden border border-slate-700/50 hover:border-primary-500/50 transition-all duration-300 hover:glow-primary" data-id="${item.id}">
                <div class="aspect-video relative overflow-hidden bg-slate-800">
                    <img src="${item.url}" alt="${item.prompt}" class="w-full h-full object-cover img-zoom" loading="lazy">
                    <div class="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent opacity-60"></div>
                    
                    <!-- Hover Actions -->
                    <div class="absolute inset-0 bg-slate-950/80 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center gap-3">
                        <button onclick="app.animateImage('${item.id}')" class="p-3 bg-primary-600 hover:bg-primary-500 rounded-full text-white transition-all hover:scale-110" title="Generate Video">
                            <i data-feather="film" class="w-5 h-5"></i>
                        </button>
                        <button onclick="app.downloadImage('${item.url}')" class="p-3 bg-slate-700 hover:bg-slate-600 rounded-full text-white transition-all hover:scale-110" title="Download">
                            <i data-feather="download" class="w-5 h-5"></i>
                        </button>
                        <button onclick="app.deleteItem('${item.id}')" class="p-3 bg-red-500/20 hover:bg-red-500/40 rounded-full text-red-400 transition-all hover:scale-110" title="Delete">
                            <i data-feather="trash-2" class="w-5 h-5"></i>
                        </button>
                    </div>
                    
                    ${item.type === 'video' ? `
                    <div class="absolute top-3 right-3 bg-secondary-500/90 text-white px-2 py-1 rounded text-xs font-bold flex items-center gap-1">
                        <i data-feather="video" class="w-3 h-3"></i> VIDEO
                    </div>
                    ` : ''}
                </div>
                <div class="p-4 space-y-2">
                    <p class="text-sm text-slate-300 line-clamp-2 font-medium">${item.prompt}</p>
                    <div class="flex items-center justify-between text-xs text-slate-500">
                        <span>${Utils.formatDate(new Date(item.timestamp))}</span>
                        <span class="font-mono">Seed: ${item.seed || 'N/A'}</span>
                    </div>
                </div>
            </div>
        `;
    }
};
// Main Application Logic
class DreamMachineApp {
    constructor() {
        this.controls = null;
        this.preview = null;
        this.init();
    }

    init() {
        this.waitForComponents().then(() => {
            this.bindEvents();
            this.loadHistory();
        });
    }

    async waitForComponents() {
        return new Promise((resolve) => {
            const check = () => {
                this.controls = document.querySelector('generator-controls');
                this.preview = document.querySelector('generator-preview');
                if (this.controls && this.preview) {
                    resolve();
                } else {
                    setTimeout(check, 50);
                }
            };
            check();
        });
    }

    bindEvents() {
        // Listen for custom events from web components
        document.addEventListener('generate-image', () => this.generateImage());
        document.addEventListener('generate-video', () => this.generateVideoFromCurrent());
        document.addEventListener('enhance-prompt', () => this.enhancePrompt());
        document.addEventListener('ratio-change', (e) => this.setAspectRatio(e.detail.ratio));

        // Settings changes from shadow DOM - use capture to catch all
        document.addEventListener('input', (e) => {
            if (e.target.hasAttribute('data-setting')) {
                const key = e.target.getAttribute('data-setting');
                const value = e.target.type === 'checkbox' ? e.target.checked : (parseFloat(e.target.value) || e.target.value);
                AppState.settings[key] = value;
            }
        }, true);

        document.addEventListener('change', (e) => {
            if (e.target.hasAttribute('data-setting')) {
                const key = e.target.getAttribute('data-setting');
                const value = e.target.type === 'checkbox' ? e.target.checked : (parseFloat(e.target.value) || e.target.value);
                AppState.settings[key] = value;
            }
        }, true);
    }

    setAspectRatio(ratio) {
        const ratios = {
            '1:1': [1024, 1024],
            '16:9': [1024, 576],
            '9:16': [576, 1024],
            '4:3': [1024, 768],
            '3:4': [768, 1024]
        };
        
        const [w, h] = ratios[ratio] || ratios['1:1'];
        AppState.settings.width = w;
        AppState.settings.height = h;
    }

    async generateImage() {
        if (!this.controls || !this.preview) return;
        
        const prompt = this.controls.getPrompt();
        
        if (!prompt.trim()) {
            // Visual feedback for empty prompt
            this.controls.shadowRoot.getElementById('prompt-input')?.classList.add('border-red-500');
            setTimeout(() => {
                this.controls.shadowRoot.getElementById('prompt-input')?.classList.remove('border-red-500');
            }, 2000);
            return;
        }

        const negativePrompt = this.controls.getNegativePrompt();
        
        AppState.isGenerating = true;
        this.preview.setLoading(true, 'Generating Image...');
        
        try {
            const result = await APIService.generateImage(prompt, negativePrompt, AppState.settings);
            AppState.currentImage = result;
            
            // Save to history
            AppState.history.unshift(result);
            localStorage.setItem('generationHistory', JSON.stringify(AppState.history));
            
            this.renderPreview(result);
            this.updateGallery();
            this.preview.showVideoControls(true);
            
        } catch (error) {
            this.preview.setContent(`
                <div class="flex flex-col items-center justify-center space-y-3 p-8 text-red-400">
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                    <p class="text-center">Generation failed. Please try again.</p>
                </div>
            `);
            console.error('Generation error:', error);
        } finally {
            AppState.isGenerating = false;
        }
    }
    renderPreview(item) {
        if (!this.preview) return;
        
        const content = `
            <div style="position: relative; width: 100%; height: 100%; min-height: 400px; background: #0f172a; border-radius: 1rem; overflow: hidden; border: 1px solid #334155;">
                <img src="${item.url}" style="width: 100%; height: 100%; object-fit: contain;" alt="Generated">
                
                <!-- Action Bar -->
                <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 1rem; background: linear-gradient(to top, #020617, transparent);">
                    <div style="display: flex; align-items: center; justify-content: space-between;">
                        <div style="display: flex; gap: 0.5rem;">
                            <button onclick="app.generateVideoFromCurrent()" style="padding: 0.5rem 1rem; background: #0891b2; color: white; border-radius: 0.5rem; font-size: 0.875rem; font-weight: 500; display: flex; align-items: center; gap: 0.5rem; border: none; cursor: pointer;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><line x1="7" y1="2" x2="7" y2="22"/><line x1="17" y1="2" x2="17" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="2" y1="7" x2="7" y2="7"/><line x1="2" y1="17" x2="7" y2="17"/><line x1="17" y1="17" x2="22" y2="17"/><line x1="17" y1="7" x2="22" y2="7"/></svg>
                                Animate to Video
                            </button>
                            <button onclick="app.downloadImage('${item.url}')" style="padding: 0.5rem 1rem; background: #334155; color: white; border-radius: 0.5rem; font-size: 0.875rem; font-weight: 500; border: none; cursor: pointer;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                            </button>
                        </div>
                        <div style="font-size: 0.75rem; color: #94a3b8; font-family: monospace;">
                            ${item.width || 1024}x${item.height || 1024}
                        </div>
                    </div>
                </div>
                
                <!-- Info Overlay -->
                <div style="position: absolute; top: 1rem; left: 1rem; max-width: 28rem;">
                    <div style="background: rgba(15, 23, 42, 0.8); backdrop-filter: blur(8px); padding: 0.5rem 0.75rem; border-radius: 0.5rem; font-size: 0.75rem; color: #cbd5e1; border: 1px solid rgba(255,255,255,0.1);">
                        <span style="color: #64748b;">Prompt:</span> ${item.prompt.substring(0, 100)}${item.prompt.length > 100 ? '...' : ''}
                    </div>
                </div>
            </div>
        `;
        
        this.preview.setContent(content);
    }
    async generateVideoFromCurrent() {
        if (!AppState.currentImage || !this.preview) return;
        
        this.preview.setLoading(true, 'Generating Video... This may take a minute');
        
        try {
            const result = await APIService.generateVideo(
                AppState.currentImage.url,
                AppState.currentImage.prompt + ', cinematic motion, smooth animation',
                AppState.settings
            );
            
            AppState.currentVideo = result;
            
            // Update history
            AppState.history.unshift(result);
            localStorage.setItem('generationHistory', JSON.stringify(AppState.history));
            
            this.renderVideoPreview(result);
            this.updateGallery();
            
        } catch (error) {
            this.preview.setContent(`
                <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 0.75rem; padding: 2rem; color: #f87171;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                    <p>Video generation failed.</p>
                </div>
            `);
        }
    }

    renderVideoPreview(item) {
        if (!this.preview) return;
        
        const content = `
            <div style="position: relative; width: 100%; height: 100%; min-height: 400px; background: black; border-radius: 1rem; overflow: hidden; border: 1px solid rgba(6, 182, 212, 0.3);">
                <div style="position: relative; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                    <img src="${item.videoUrl}" style="width: 100%; height: 100%; object-fit: contain;" alt="Video thumbnail">
                    
                    <!-- Play Button Overlay -->
                    <div style="position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,0.4);">
                        <button style="width: 5rem; height: 5rem; background: rgba(6, 182, 212, 0.9); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; border: none; cursor: pointer;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                        </button>
                    </div>
                </div>
                
                <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 1rem; background: linear-gradient(to top, black, transparent);">
                    <div style="display: flex; align-items: center; justify-content: space-between; color: white;">
                        <div style="display: flex; align-items: center; gap: 0.75rem;">
                            <span style="padding: 0.25rem 0.5rem; background: rgba(6, 182, 212, 0.2); border-radius: 0.25rem; font-size: 0.75rem; font-family: monospace; color: #22d3ee;">MP4</span>
                            <span style="font-size: 0.875rem;">${item.duration}s @ 24fps</span>
                        </div>
                        <button onclick="app.downloadImage('${item.videoUrl}')" style="padding: 0.5rem; background: rgba(255,255,255,0.1); border-radius: 0.5rem; border: none; cursor: pointer; color: white;">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        this.preview.setContent(content);
    }
animateImage(id) {
        const item = AppState.history.find(h => h.id === id);
        if (item && item.type === 'image') {
            AppState.currentImage = item;
            this.generateVideoFromCurrent();
        }
    }

    downloadImage(url) {
        const a = document.createElement('a');
        a.href = url;
        a.download = `dream-machine-${Date.now()}.png`;
        a.target = '_blank';
        a.click();
    }

    deleteItem(id) {
        AppState.history = AppState.history.filter(h => h.id !== id);
        localStorage.setItem('generationHistory', JSON.stringify(AppState.history));
        this.updateGallery();
    }
    updateGallery() {
        const gallery = document.querySelector('gallery-grid');
        if (!gallery) return;
        
        gallery.updateCount(AppState.history.length);
        
        if (AppState.history.length === 0) {
            gallery.setContent(`
                <div style="grid-column: 1 / -1; text-align: center; padding: 3rem; color: #64748b;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" style="margin: 0 auto 1rem; opacity: 0.3;"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                    <p>No generations yet</p>
                    <p style="font-size: 0.875rem; margin-top: 0.5rem; opacity: 0.7;">Your creations will be saved here automatically</p>
                </div>
            `);
        } else {
            const cards = AppState.history.map(item => this.createImageCard(item)).join('');
            gallery.setContent(cards);
        }
    }

    createImageCard(item) {
        const isVideo = item.type === 'video';
        return `
            <div style="position: relative; background: rgba(15, 23, 42, 0.5); border-radius: 0.75rem; overflow: hidden; border: 1px solid rgba(51, 65, 85, 0.5); transition: all 0.3s;" onmouseover="this.style.borderColor='rgba(139, 92, 246, 0.5)'" onmouseout="this.style.borderColor='rgba(51, 65, 85, 0.5)'">
                <div style="aspect-ratio: 16/9; position: relative; overflow: hidden; background: #1e293b;">
                    <img src="${item.url}" alt="${item.prompt}" style="width: 100%; height: 100%; object-fit: cover; transition: transform 0.5s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'" loading="lazy">
                    <div style="position: absolute; inset: 0; background: linear-gradient(to top, #020617, transparent); opacity: 0.6;"></div>
                    
                    <!-- Hover Actions -->
                    <div style="position: absolute; inset: 0; background: rgba(2, 6, 23, 0.8); opacity: 0; transition: opacity 0.3s; display: flex; align-items: center; justify-content: center; gap: 0.75rem;" onmouseover="this.style.opacity='1'" onmouseout="this.style.opacity='0'">
                        ${!isVideo ? `<button onclick="app.animateImage('${item.id}')" style="padding: 0.75rem; background: #7c3aed; border-radius: 50%; color: white; border: none; cursor: pointer; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" title="Generate Video">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><line x1="7" y1="2" x2="7" y2="22"/><line x1="17" y1="2" x2="17" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="2" y1="7" x2="7" y2="7"/><line x1="2" y1="17" x2="7" y2="17"/><line x1="17" y1="17" x2="22" y2="17"/><line x1="17" y1="7" x2="22" y2="7"/></svg>
                        </button>` : ''}
                        <button onclick="app.downloadImage('${item.url}')" style="padding: 0.75rem; background: #334155; border-radius: 50%; color: white; border: none; cursor: pointer; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" title="Download">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                        </button>
                        <button onclick="app.deleteItem('${item.id}')" style="padding: 0.75rem; background: rgba(239, 68, 68, 0.2); border-radius: 50%; color: #f87171; border: none; cursor: pointer; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.1)'" title="Delete">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                        </button>
                    </div>
                    
                    ${isVideo ? `
                    <div style="position: absolute; top: 0.75rem; right: 0.75rem; background: rgba(6, 182, 212, 0.9); color: white; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.625rem; font-weight: bold; display: flex; align-items: center; gap: 0.25rem;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>
                        VIDEO
                    </div>
                    ` : ''}
                </div>
                <div style="padding: 1rem;">
                    <p style="font-size: 0.875rem; color: #cbd5e1; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; font-weight: 500;">${item.prompt}</p>
                    <div style="display: flex; align-items: center; justify-content: space-between; font-size: 0.75rem; color: #64748b; margin-top: 0.5rem;">
                        <span>${Utils.formatDate(new Date(item.timestamp))}</span>
                        <span style="font-family: monospace;">Seed: ${item.seed || 'N/A'}</span>
                    </div>
                </div>
            </div>
        `;
    }

    loadHistory() {
        this.updateGallery();
    }
enhancePrompt() {
        if (!this.controls) return;
        
        const current = this.controls.getPrompt();
        const enhancers = [
            '8k resolution, photorealistic, highly detailed, professional photography',
            'cinematic lighting, unreal engine 5, octane render',
            'masterpiece, best quality, intricate details',
            'trending on artstation, sharp focus, vivid colors'
        ];
        
        const randomEnhancer = enhancers[Math.floor(Math.random() * enhancers.length)];
        const newValue = current ? `${current}, ${randomEnhancer}` : randomEnhancer;
        this.controls.setPrompt(newValue);
        
        // Visual feedback
        const input = this.controls.shadowRoot.getElementById('prompt-input');
        if (input) {
            input.style.boxShadow = '0 0 0 2px #06b6d4';
            setTimeout(() => input.style.boxShadow = '', 500);
        }
    }

    clearHistory() {
        AppState.history = [];
        localStorage.removeItem('generationHistory');
        this.updateGallery();
    }
}

// Initialize
const app = new DreamMachineApp();

// Expose to window for onclick handlers
window.app = app;