File size: 28,300 Bytes
f462b1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
// ══════════════════════════════════════════════════════════════════════════════
// Chahua Markdown Presenter - Slide Editor
// In-Presentation Slide Editing System with Drag & Drop
// ══════════════════════════════════════════════════════════════════════════════
// Company: Chahua Development Co., Ltd.
// Version: 2.1.0
// License: MIT
// ══════════════════════════════════════════════════════════════════════════════

import { DragDropManager } from './drag-drop-manager.js';
import { PersistentStorage } from '../../shared/persistent-storage.js';
import { ContentFingerprint } from '../../shared/content-fingerprint.js';
import { setDisplayMode, getDisplayMode } from './presentation-config.js';
import { 
    switchToEditorMode, 
    switchToPresentationMode,
    getModeManager 
} from './mode-manager.js';

/**

 * Slide Editor - แก้ไขสไลด์แบบ inline ใน Presentation Mode

 * พร้อมระบบลากย้ายตำแหน่งและบันทึกถาวร

 */
export class SlideEditor {
    constructor() {
        this.isEditMode = false;
        this.isDragMode = false;
        this.currentSlideIndex = -1;
        this.currentFilePath = null;
        this.slideOverrides = new Map(); // เก็บการแก้ไขแยกตามสไลด์
        this.originalContent = null;
        this.hasUnsavedChanges = false;
        
        // DOM Elements
        this.editBtn = document.getElementById('editSlideBtn');
        this.saveBtn = document.getElementById('saveSlideBtn');
        this.cancelBtn = document.getElementById('cancelEditBtn');
        this.stage = document.getElementById('stage');
        
        // Position Controls
        this.positionControls = document.getElementById('positionControls');
        this.toggleSafeZoneBtn = document.getElementById('toggleSafeZoneBtn');
        this.toggleSnapGridBtn = document.getElementById('toggleSnapGridBtn');
        this.resetPositionsBtn = document.getElementById('resetPositionsBtn');
        this.exportSettingsBtn = document.getElementById('exportSettingsBtn');
        this.positionIndicator = document.getElementById('positionIndicator');
        
        // Managers
        this.dragDropManager = new DragDropManager();
        this.persistentStorage = new PersistentStorage();
        
        this.init();
    }

    /**

     * Initialize editor

     */
    init() {
        if (!this.editBtn || !this.saveBtn || !this.cancelBtn) {
            console.warn('[SlideEditor] Required buttons not found');
            return;
        }

        // Event listeners
        this.editBtn.addEventListener('click', () => this.toggleEditMode());
        this.saveBtn.addEventListener('click', () => this.saveChanges());
        this.cancelBtn.addEventListener('click', () => this.cancelEdit());
        
        // Position control listeners
        if (this.toggleSafeZoneBtn) {
            this.toggleSafeZoneBtn.addEventListener('click', () => this.toggleSafeZone());
        }
        if (this.toggleSnapGridBtn) {
            this.toggleSnapGridBtn.addEventListener('click', () => this.toggleSnapGrid());
        }
        if (this.resetPositionsBtn) {
            this.resetPositionsBtn.addEventListener('click', () => this.resetAllPositions());
        }
        if (this.exportSettingsBtn) {
            this.exportSettingsBtn.addEventListener('click', () => this.exportAllSettings());
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            if (!this.isEditMode) return;

            // Ctrl/Cmd + S = Save
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                this.saveChanges();
            }

            // ESC = Cancel
            if (e.key === 'Escape') {
                e.preventDefault();
                this.cancelEdit();
            }
        });

        console.log('[SlideEditor] Initialized');
    }

    /**

     * Show edit button when in presentation mode

     */
    showEditButton() {
        if (this.editBtn) {
            this.editBtn.classList.remove('hidden');
        }
    }

    /**

     * Hide edit button

     */
    hideEditButton() {
        if (this.editBtn) {
            this.editBtn.classList.add('hidden');
        }
        this.exitEditMode();
    }

    /**

     * Set current slide index

     */
    setCurrentSlide(index) {
        this.currentSlideIndex = index;
    }

    /**

     * Toggle edit mode

     */
    toggleEditMode() {
        if (this.isEditMode) {
            this.exitEditMode();
        } else {
            this.enterEditMode();
        }
    }

    /**

     * Enter edit mode

     */
    /**

     * Enter edit mode

     */
    enterEditMode() {
        if (this.currentSlideIndex < 0) {
            console.warn('[SlideEditor] No slide selected');
            return;
        }

        // สลับไปโหมด editor และปิดโหมดอื่นทั้งหมด
        switchToEditorMode();

        this.isEditMode = true;
        this.hasUnsavedChanges = false;

        // Save original content
        const activeScene = this.stage.querySelector('.scene.active');
        if (!activeScene) {
            console.warn('[SlideEditor] No active scene found');
            return;
        }

        this.originalContent = activeScene.cloneNode(true);
        
        // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง detach ที่นี่

        // Make content editable
        this.makeContentEditable(activeScene);

        // Update UI
        this.stage.classList.add('slide-editable');
        this.editBtn.classList.add('active');
        this.showEditIndicator();
        
        // Mode Manager จัดการ Safe Zone แล้ว ไม่ต้องแสดงที่นี่

        console.log(`[SlideEditor] Edit mode entered for slide ${this.currentSlideIndex}`);
    }

    /**

     * Exit edit mode (with unsaved changes check)

     */
    async exitEditMode() {
        if (!this.isEditMode) return;

        // ถ้ามีการแก้ไขที่ยังไม่บันทึก ให้ถามผู้ใช้
        if (this.hasUnsavedChanges) {
            const result = await this.showExitConfirmation('Edit Mode', 'You have unsaved changes.');
            
            if (result === 'cancel') {
                // ยกเลิก ไม่ออกจาก Edit Mode
                return;
            } else if (result === 'save') {
                // บันทึกก่อนออก
                await this.saveCurrentSlide();
            }
            // ถ้าเลือก 'discard' ก็ออกเลยโดยไม่บันทึก
        }

        this.isEditMode = false;

        // กลับไปโหมด presentation และปิดโหมดอื่นทั้งหมด
        switchToPresentationMode();

        // Remove contenteditable
        const activeScene = this.stage.querySelector('.scene.active');
        if (activeScene) {
            this.makeContentNonEditable(activeScene);
        }

        // Update UI
        this.stage.classList.remove('slide-editable');
        this.editBtn.classList.remove('active');
        this.hideEditIndicator();
        this.hideSaveButtons();
        
        // Mode Manager จัดการ Safe Zone และ Smart Layout แล้ว

        this.originalContent = null;
        this.hasUnsavedChanges = false;

        console.log('[SlideEditor] Edit mode exited');
    }

    /**

     * Show exit confirmation dialog

     * @param {string} modeName - ชื่อโหมด

     * @param {string} message - ข้อความเพิ่มเติม

     * @returns {Promise<string>} 'save', 'discard', หรือ 'cancel'

     */
    async showExitConfirmation(modeName, message = '') {
        return new Promise((resolve) => {
            const dialog = document.createElement('div');
            dialog.className = 'exit-confirmation-dialog';
            dialog.innerHTML = `

                <div class="exit-confirmation-overlay"></div>

                <div class="exit-confirmation-content">

                    <div class="exit-confirmation-header">

                        <h3>Exit ${modeName}?</h3>

                    </div>

                    <div class="exit-confirmation-body">

                        <p class="warning-text">${message}</p>

                        <p>Do you want to save your changes?</p>

                    </div>

                    <div class="exit-confirmation-footer">

                        <button class="btn-exit-save" data-action="save">

                            Save & Exit

                        </button>

                        <button class="btn-exit-discard" data-action="discard">

                            Discard Changes

                        </button>

                        <button class="btn-exit-cancel" data-action="cancel">

                            Cancel

                        </button>

                    </div>

                </div>

            `;
            
            document.body.appendChild(dialog);
            
            // Handle button clicks
            dialog.querySelectorAll('button').forEach(btn => {
                btn.addEventListener('click', () => {
                    const action = btn.dataset.action;
                    document.body.removeChild(dialog);
                    resolve(action);
                });
            });
            
            // ESC to cancel
            const escHandler = (e) => {
                if (e.key === 'Escape') {
                    document.body.removeChild(dialog);
                    document.removeEventListener('keydown', escHandler);
                    resolve('cancel');
                }
            };
            document.addEventListener('keydown', escHandler);
        });
    }

    /**

     * Make scene content editable

     */
    makeContentEditable(scene) {
        // Find all editable elements
        const editableElements = scene.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote');
        
        editableElements.forEach((el, index) => {
            el.setAttribute('contenteditable', 'true');
            el.setAttribute('data-editable-id', `edit-${index}`);
            el.setAttribute('data-placeholder', 'Click to edit...');
            
            // Track changes
            el.addEventListener('input', () => this.onContentChange());
            el.addEventListener('blur', () => this.onContentChange());
        });
    }

    /**

     * Remove contenteditable

     */
    makeContentNonEditable(scene) {
        const editableElements = scene.querySelectorAll('[contenteditable="true"]');
        
        editableElements.forEach(el => {
            el.removeAttribute('contenteditable');
            el.removeAttribute('data-editable-id');
            el.removeAttribute('data-placeholder');
        });
    }

    /**

     * Handle content change

     */
    onContentChange() {
        if (!this.hasUnsavedChanges) {
            this.hasUnsavedChanges = true;
            this.showSaveButtons();
        }
    }

    /**

     * Save changes to current slide

     */
    saveChanges() {
        if (!this.isEditMode || this.currentSlideIndex < 0) return;

        const activeScene = this.stage.querySelector('.scene.active');
        if (!activeScene) return;

        // Extract edited content
        const editedContent = this.extractEditedContent(activeScene);

        // Save to overrides map
        this.slideOverrides.set(this.currentSlideIndex, {
            timestamp: Date.now(),
            content: editedContent,
            html: activeScene.innerHTML
        });

        console.log(`[SlideEditor] Saved changes for slide ${this.currentSlideIndex}`, editedContent);

        // Exit edit mode
        this.exitEditMode();

        // Show success notification
        this.showNotification('✓ Slide saved', 'success');
    }

    /**

     * Cancel edit and revert changes

     */
    cancelEdit() {
        if (!this.isEditMode || !this.originalContent) return;

        const activeScene = this.stage.querySelector('.scene.active');
        if (activeScene && this.originalContent) {
            // Restore original content
            activeScene.parentNode.replaceChild(this.originalContent.cloneNode(true), activeScene);
            
            // Re-add active class
            const restoredScene = this.stage.querySelector('.scene[data-scene]');
            if (restoredScene) {
                restoredScene.classList.add('active');
            }
        }

        this.exitEditMode();
        this.showNotification('✗ Changes cancelled', 'warning');
    }

    /**

     * Extract edited content from scene

     */
    extractEditedContent(scene) {
        const content = {};
        
        // Extract text from editable elements
        const editables = scene.querySelectorAll('[data-editable-id]');
        editables.forEach(el => {
            const id = el.getAttribute('data-editable-id');
            content[id] = {
                tag: el.tagName.toLowerCase(),
                text: el.textContent.trim(),
                html: el.innerHTML
            };
        });

        return content;
    }

    /**

     * Apply saved overrides to a slide

     */
    applyOverrides(slideIndex, scene) {
        if (!this.slideOverrides.has(slideIndex)) return false;

        const override = this.slideOverrides.get(slideIndex);
        
        // Apply saved HTML
        if (override.html) {
            scene.innerHTML = override.html;
            console.log(`[SlideEditor] Applied overrides to slide ${slideIndex}`);
            return true;
        }

        return false;
    }

    /**

     * Check if slide has overrides

     */
    hasOverrides(slideIndex) {
        return this.slideOverrides.has(slideIndex);
    }

    /**

     * Get all overrides

     */
    getAllOverrides() {
        return Array.from(this.slideOverrides.entries()).map(([index, data]) => ({
            slideIndex: index,
            ...data
        }));
    }

    /**

     * Clear override for specific slide

     */
    clearOverride(slideIndex) {
        this.slideOverrides.delete(slideIndex);
    }

    /**

     * Clear all overrides

     */
    clearAllOverrides() {
        this.slideOverrides.clear();
    }

    /**

     * Export overrides as JSON

     */
    exportOverrides() {
        const data = this.getAllOverrides();
        return JSON.stringify(data, null, 2);
    }

    /**

     * Import overrides from JSON

     */
    importOverrides(jsonString) {
        try {
            const data = JSON.parse(jsonString);
            data.forEach(item => {
                this.slideOverrides.set(item.slideIndex, {
                    timestamp: item.timestamp,
                    content: item.content,
                    html: item.html
                });
            });
            console.log(`[SlideEditor] Imported ${data.length} overrides`);
            return true;
        } catch (error) {
            console.error('[SlideEditor] Failed to import overrides:', error);
            return false;
        }
    }

    /**

     * Show edit mode indicator

     */
    showEditIndicator() {
        let indicator = document.getElementById('editModeIndicator');
        if (!indicator) {
            indicator = document.createElement('div');
            indicator.id = 'editModeIndicator';
            indicator.className = 'edit-mode-indicator';
            indicator.textContent = '✎ Edit Mode';
            this.stage.appendChild(indicator);
        }
    }

    /**

     * Hide edit mode indicator

     */
    hideEditIndicator() {
        const indicator = document.getElementById('editModeIndicator');
        if (indicator) {
            indicator.remove();
        }
    }

    /**

     * Show save/cancel buttons

     */
    showSaveButtons() {
        if (this.saveBtn) this.saveBtn.classList.remove('hidden');
        if (this.cancelBtn) this.cancelBtn.classList.remove('hidden');
    }

    /**

     * Hide save/cancel buttons

     */
    hideSaveButtons() {
        if (this.saveBtn) this.saveBtn.classList.add('hidden');
        if (this.cancelBtn) this.cancelBtn.classList.add('hidden');
    }

    /**

     * Show notification

     */
    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `slide-edit-notification notification-${type}`;
        notification.textContent = message;
        notification.style.cssText = `

            position: fixed;

            top: 5rem;

            left: 50%;

            transform: translateX(-50%);

            z-index: 1000;

            background: ${type === 'success' ? 'rgba(16, 185, 129, 0.95)' : 

                         type === 'warning' ? 'rgba(245, 158, 11, 0.95)' : 

                         'rgba(59, 130, 246, 0.95)'};

            color: white;

            padding: 0.75rem 1.5rem;

            border-radius: 0.5rem;

            font-weight: 600;

            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);

            animation: slideDown 0.3s ease-out;

        `;

        document.body.appendChild(notification);

        // Remove after 3 seconds
        setTimeout(() => {
            notification.style.animation = 'slideUp 0.3s ease-out';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    /**

     * Reset editor state

     */
    reset() {
        this.exitEditMode();
        this.exitDragMode();
        this.currentSlideIndex = -1;
        this.hideEditButton();
        this.hidePositionControls();
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // DRAG & DROP METHODS
    // ═══════════════════════════════════════════════════════════════════════════

    /**

     * เข้าสู่ Drag Mode

     */
    /**

     * เข้าสู่ Drag Mode

     */
    enterDragMode() {
        const activeScene = this.stage?.querySelector('.scene.active');
        if (!activeScene) return;

        // สลับไปโหมด editor และปิดโหมดอื่นทั้งหมด
        switchToEditorMode();

        this.isDragMode = true;
        
        // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง detach ที่นี่
        
        this.dragDropManager.enableDragging(activeScene);
        this.showPositionControls();
        
        // เปลี่ยนสีปุ่ม edit
        if (this.editBtn) {
            this.editBtn.style.background = 'rgba(139, 92, 246, 0.9)'; // สีม่วง
        }
        
        this.showNotification('⊕ Drag Mode - ลากเพื่อย้ายตำแหน่งบรรทัด', 'info');
    }

    /**

     * ออกจาก Drag Mode

     */
    exitDragMode() {
        const activeScene = this.stage?.querySelector('.scene.active');
        if (activeScene) {
            this.dragDropManager.disableDragging(activeScene);
        }

        // กลับไปโหมด presentation และปิดโหมดอื่นทั้งหมด
        switchToPresentationMode();

        this.isDragMode = false;
        this.hidePositionControls();
        
        // Mode Manager จัดการ Smart Layout แล้ว ไม่ต้อง reattach ที่นี่
        
        // คืนสีปุ่ม edit
        if (this.editBtn) {
            this.editBtn.style.background = '';
        }
    }

    /**

     * Toggle Drag Mode

     */
    toggleDragMode() {
        if (this.isDragMode) {
            this.exitDragMode();
        } else {
            // ออกจาก Edit Mode ก่อน (ถ้ากำลัง edit อยู่)
            if (this.isEditMode) {
                this.exitEditMode();
            }
            this.enterDragMode();
        }
    }

    /**

     * แสดง Position Controls

     */
    showPositionControls() {
        if (this.positionControls) {
            this.positionControls.classList.remove('hidden');
        }
    }

    /**

     * ซ่อน Position Controls

     */
    hidePositionControls() {
        if (this.positionControls) {
            this.positionControls.classList.add('hidden');
        }
    }

    /**

     * Toggle Safe Zone

     */
    toggleSafeZone() {
        const isActive = this.dragDropManager.showSafeZone;
        this.dragDropManager.toggleSafeZone(!isActive);
        
        if (this.toggleSafeZoneBtn) {
            if (!isActive) {
                this.toggleSafeZoneBtn.classList.add('active');
                this.showNotification('✓ Safe Zone เปิด', 'success');
            } else {
                this.toggleSafeZoneBtn.classList.remove('active');
                this.showNotification('✗ Safe Zone ปิด', 'info');
            }
        }
    }

    /**

     * Toggle Snap to Grid

     */
    toggleSnapGrid() {
        const isActive = this.dragDropManager.snapToGrid;
        this.dragDropManager.toggleSnapToGrid(!isActive);
        
        if (this.toggleSnapGridBtn) {
            if (!isActive) {
                this.toggleSnapGridBtn.classList.add('active');
                this.showNotification('✓ Snap to Grid เปิด', 'success');
            } else {
                this.toggleSnapGridBtn.classList.remove('active');
                this.showNotification('✗ Snap to Grid ปิด', 'info');
            }
        }
    }

    /**

     * รีเซ็ตตำแหน่งทั้งหมดของสไลด์ปัจจุบัน

     */
    resetAllPositions() {
        if (!confirm('รีเซ็ตตำแหน่งและการแก้ไขทั้งหมดของสไลด์นี้?\n(การตั้งค่าจะถูกลบถาวร)')) {
            return;
        }

        const activeScene = this.stage?.querySelector('.scene.active');
        if (!activeScene) return;

        // รีเซ็ตตำแหน่ง
        const elements = activeScene.querySelectorAll('.draggable-content');
        elements.forEach(element => {
            this.dragDropManager.resetPosition(element);
        });

        // ลบการแก้ไขเนื้อหา
        if (this.currentSlideIndex >= 0) {
            this.slideOverrides.delete(this.currentSlideIndex);
        }

        // ลบจาก localStorage
        if (this.currentFilePath && this.currentSlideIndex >= 0) {
            this.persistentStorage.clearSlide(this.currentFilePath, this.currentSlideIndex);
        }

        // ลบข้อมูล positions จาก dragDropManager
        this.dragDropManager.clearAllPositions();

        this.showNotification('✓ รีเซ็ตทั้งหมดเรียบร้อย', 'success');
    }

    /**

     * Export การตั้งค่าทั้งหมด

     */
    exportAllSettings() {
        if (!this.currentFilePath) {
            this.showNotification('⚠ กรุณาเปิดไฟล์ก่อน', 'warning');
            return;
        }

        const totalSlides = this.getTotalSlides();
        this.persistentStorage.downloadJSON(this.currentFilePath, totalSlides);
        this.showNotification('✓ ส่งออกการตั้งค่าเรียบร้อย', 'success');
    }

    /**

     * นับจำนวน slides ทั้งหมด

     */
    getTotalSlides() {
        // ควร implement ตามโครงสร้างจริง
        return 10; // placeholder
    }

    /**

     * ตั้งค่าไฟล์ปัจจุบัน

     */
    setCurrentFile(filePath) {
        this.currentFilePath = filePath;
        this.persistentStorage.setCurrentFile(filePath);
    }

    /**

     * Apply positions จาก storage

     */
    applyPositions(slideIndex, scene) {
        if (!this.currentFilePath) return false;

        const positions = this.persistentStorage.loadPositions(this.currentFilePath, slideIndex);
        if (!positions) return false;

        this.dragDropManager.loadPositions(positions);
        return true;
    }

    /**

     * Save positions ไปยัง storage

     */
    savePositions() {
        if (!this.currentFilePath || this.currentSlideIndex < 0) return;

        const positions = this.dragDropManager.exportPositions();
        this.persistentStorage.savePositions(
            this.currentFilePath,
            this.currentSlideIndex,
            positions
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // CONTENT FINGERPRINTING
    // ═══════════════════════════════════════════════════════════════════════════

    /**

     * สร้าง fingerprint map สำหรับ slide

     */
    createFingerprintMap(scene) {
        return ContentFingerprint.mapSlideElements(scene);
    }

    /**

     * Match settings กับ content ใหม่

     */
    matchSettingsToContent(scene, savedSettings) {
        const elementMap = this.createFingerprintMap(scene);
        const matched = [];

        elementMap.forEach(({ element, fingerprint }) => {
            const setting = ContentFingerprint.match(fingerprint, savedSettings);
            if (setting) {
                matched.push({
                    element,
                    setting,
                    confidence: setting.matchConfidence
                });
            }
        });

        return matched;
    }
}

// CSS for notification animation
const style = document.createElement('style');
style.textContent = `

@keyframes slideDown {

    from {

        opacity: 0;

        transform: translate(-50%, -20px);

    }

    to {

        opacity: 1;

        transform: translate(-50%, 0);

    }

}



@keyframes slideUp {

    from {

        opacity: 1;

        transform: translate(-50%, 0);

    }

    to {

        opacity: 0;

        transform: translate(-50%, -20px);

    }

}

`;
document.head.appendChild(style);