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
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
/*

   ELYSIA MARKDOWN STUDIO v1.0 - Main Application

   Orchestrates all modules

*/

import Utils from "./utils.js";
import DB from "./db.js";
import Editor from "./editor.js";
import Preview from "./preview.js";
import Documents from "./documents.js";
import AITools from "./ai-tools.js";
import Export from "./export.js";
import Templates from "./templates.js";

class App {
    constructor() {
        this.currentDoc = null;
        this.currentDocId = null;
        this.unsavedChanges = false;

        // Module references
        this.editor = Editor;
        this.preview = Preview;
        this.documents = Documents;
        this.aiTools = AITools;
        this.export = Export;
        this.templates = Templates;
    }

    async init() {
        console.log("πŸ’Ž Elysia Markdown Studio v1.3.0 initializing...");

        // Initialize modules FIRST (before loadSettings!)
        this.editor.init();
        this.preview.init();
        this.documents.init();
        this.aiTools.init();
        this.export.init();
        this.templates.init();

        // Load settings (now that modules are ready)
        this.loadSettings();

        // Setup event listeners
        this.setupEventListeners();

        // Welcome message
        this.showWelcome();

        // Start auto-save AFTER everything is initialized
        const autoSave = Utils.storage.get("autoSave", true);
        if (autoSave) {
            this.editor.startAutoSave();
        }

        console.log("✨ Elysia Markdown Studio ready!");
    }

    setupEventListeners() {
        // New document - show template selection
        document.getElementById("btn-new-doc").addEventListener("click", () => {
            this.templates.showTemplatesModal();
        });

        // Save document
        document.getElementById("btn-save").addEventListener("click", () => {
            this.saveDocument();
        });

        // Settings - OPEN modal
        document.getElementById("btn-settings").addEventListener("click", () => {
            Utils.modal.open("modal-settings");
        });

        // Settings - SAVE settings
        document.getElementById("btn-save-settings").addEventListener("click", () => {
            this.saveSettings();
        });

        // Document title
        document.getElementById("doc-title").addEventListener("input", e => {
            if (this.currentDoc) {
                this.currentDoc.title = e.target.value || "Untitled Document";
                this.unsavedChanges = true;
            }
        });

        // Mobile view toggle (Editor <-> Preview)
        const mobileToggle = document.getElementById("mobile-view-toggle");
        if (mobileToggle) {
            mobileToggle.addEventListener("click", () => {
                this.toggleMobileView();
            });
        }

        // Keyboard shortcuts
        document.addEventListener("keydown", e => {
            if (e.ctrlKey || e.metaKey) {
                if (e.key === "s") {
                    e.preventDefault();
                    this.saveDocument();
                } else if (e.key === "n") {
                    e.preventDefault();
                    this.templates.showTemplatesModal();
                } else if (e.key === "/") {
                    e.preventDefault();
                    this.showKeyboardShortcuts();
                }
            }
        });

        // Before unload warning
        window.addEventListener("beforeunload", e => {
            if (this.unsavedChanges) {
                e.preventDefault();
                e.returnValue = "";
            }
        });
    }

    async newDocument(templateName = null) {
        if (this.unsavedChanges) {
            const save = confirm("Save current document before creating new one?");
            if (save) {
                await this.saveDocument();
            }
        }

        // Get template content
        let content = "";
        if (templateName) {
            const template = await this.templates.getTemplate(templateName);
            content = template?.content || "";
        }

        // Create new document
        this.currentDoc = {
            id: Utils.uuid(),
            title: "Untitled Document",
            content,
            tags: [],
            favorite: false,
            createdAt: Date.now(),
            updatedAt: Date.now(),
            wordCount: 0,
            charCount: 0
        };

        this.currentDocId = null; // Not saved yet
        this.unsavedChanges = false;

        // Update UI
        document.getElementById("doc-title").value = this.currentDoc.title;
        this.editor.setContent(content);
        this.editor.currentDoc = this.currentDoc;

        Utils.toast.info("New document created");
    }

    async loadDocument(id) {
        if (this.unsavedChanges) {
            const save = confirm("Save current document before loading another?");
            if (save) {
                await this.saveDocument();
            }
        }

        const doc = await DB.getDocument(id);
        if (!doc) {
            Utils.toast.error("Document not found");
            return;
        }

        this.currentDoc = doc;
        this.currentDocId = id;
        this.unsavedChanges = false;

        // Update UI
        document.getElementById("doc-title").value = doc.title;
        this.editor.setContent(doc.content);
        this.editor.currentDoc = doc;

        // Update sidebar highlight
        this.documents.updateActiveDoc(id);

        Utils.toast.success(`Loaded: ${doc.title}`);
    }

    async saveDocument(silent = false) {
        const content = this.editor.getContent();
        const title = document.getElementById("doc-title").value || "Untitled Document";

        if (!content && !silent) {
            Utils.toast.warning("Document is empty. Add some content before saving!");
            return;
        }

        try {
            if (this.currentDocId) {
                // Update existing
                await DB.updateDocument(this.currentDocId, {
                    title,
                    content,
                    updatedAt: Date.now()
                });

                if (!silent) Utils.toast.success("Document saved!");
            } else {
                // Check for potential duplicates before creating
                const existingDocs = await DB.getAllDocuments();
                const duplicate = existingDocs.find(
                    doc => doc.title.toLowerCase() === title.toLowerCase() && doc.content === content
                );

                if (duplicate && !silent) {
                    const shouldCreate = confirm(
                        `A document with the title "${title}" and identical content already exists.\n\n` +
                            "Do you want to create it anyway?"
                    );
                    if (!shouldCreate) return;
                }

                // Create new
                const doc = await DB.createDocument({
                    title,
                    content
                });

                this.currentDocId = doc.id;
                this.currentDoc = doc;

                if (!silent) Utils.toast.success("Document created and saved!");
            }

            this.unsavedChanges = false;

            // Refresh documents list
            this.documents.loadDocuments();
        } catch (err) {
            console.error("Save failed:", err);
            Utils.toast.error("Failed to save document");
        }
    }

    loadSettings() {
        const apiKey = Utils.storage.get("apiKey");
        const model = Utils.storage.get("model", "anthropic/claude-sonnet-4.5");
        const previewTheme = Utils.storage.get("previewTheme", "elysia");
        const autoSave = Utils.storage.get("autoSave", true);
        const livePreview = Utils.storage.get("livePreview", true);

        // Populate settings form
        if (document.getElementById("api-key")) {
            document.getElementById("api-key").value = apiKey || "";
        }
        if (document.getElementById("model-select")) {
            document.getElementById("model-select").value = model;
        }
        if (document.getElementById("preview-theme")) {
            document.getElementById("preview-theme").value = previewTheme;
        }
        if (document.getElementById("auto-save")) {
            document.getElementById("auto-save").checked = autoSave;
        }
        if (document.getElementById("live-preview")) {
            document.getElementById("live-preview").checked = livePreview;
        }

        // Apply theme
        this.preview.setTheme(previewTheme);
    }

    saveSettings() {
        const apiKey = document.getElementById("api-key").value.trim();
        const model = document.getElementById("model-select").value;
        const previewTheme = document.getElementById("preview-theme").value;
        const autoSave = document.getElementById("auto-save").checked;
        const livePreview = document.getElementById("live-preview").checked;

        // Validate API key format (OpenRouter keys start with "sk-or-")
        if (apiKey && !apiKey.startsWith("sk-or-")) {
            Utils.toast.warning("API key should start with 'sk-or-'. Please check your key.");
            return;
        }

        Utils.storage.set("apiKey", apiKey);
        Utils.storage.set("model", model);
        Utils.storage.set("previewTheme", previewTheme);
        Utils.storage.set("autoSave", autoSave);
        Utils.storage.set("livePreview", livePreview);

        // Apply theme
        this.preview.setTheme(previewTheme);

        // Restart auto-save if needed
        if (autoSave) {
            this.editor.startAutoSave();
        } else {
            this.editor.stopAutoSave();
        }

        // Update preview immediately if toggling live preview
        if (livePreview) {
            this.preview.update();
        }

        Utils.toast.success("Settings saved!");
        Utils.modal.close("modal-settings");
    }

    // Mobile view toggle (Editor <-> Preview)
    toggleMobileView() {
        const previewPane = document.querySelector(".preview-pane");
        const editorPane = document.querySelector(".editor-pane");
        const toggleBtn = document.getElementById("mobile-view-toggle");
        const toggleIcon = toggleBtn?.querySelector(".toggle-icon");
        const toggleText = toggleBtn?.querySelector(".toggle-text");

        if (!previewPane || !editorPane) return;

        const isPreviewActive = previewPane.classList.contains("active");

        if (isPreviewActive) {
            // Switch to Editor
            previewPane.classList.remove("active");
            editorPane.style.display = "block";
            if (toggleIcon) toggleIcon.textContent = "πŸ‘οΈ";
            if (toggleText) toggleText.textContent = "Preview";
        } else {
            // Switch to Preview
            this.preview.update(); // Ensure preview is current
            previewPane.classList.add("active");
            editorPane.style.display = "none";
            if (toggleIcon) toggleIcon.textContent = "✏️";
            if (toggleText) toggleText.textContent = "Editor";
        }
    }

    showWelcome() {
        const welcomeMessage = `# Welcome to Elysia Markdown Studio πŸ’Ž



Your AI-powered writing companion is ready!



## ✨ Features



- **Live Preview** - See your markdown rendered in real-time

- **AI Tools** - Summarize, improve, merge documents with Elysia's intelligence

- **Rich Markdown** - Support for tables, math (KaTeX), diagrams (Mermaid), code highlighting

- **Smart Export** - Export to Markdown, HTML, Artifact, JSON, Plain Text

- **Document Management** - Organize with tags, favorites, collections

- **Templates** - Quick start with README, Blog, Meeting Notes, and more!



## πŸš€ Quick Start



1. Click **βš™οΈ Settings** to add your OpenRouter API key (for AI features)

2. Start writing in the left pane

3. See live preview on the right

4. Use toolbar for quick formatting

5. Save with **πŸ’Ύ** or Ctrl+S

6. Access AI tools with **🧠**



## ⌨️ Keyboard Shortcuts



| Shortcut | Action |

|----------|--------|

| **Ctrl+S** | Save document |

| **Ctrl+N** | New document |

| **Ctrl+B** | Bold text |

| **Ctrl+I** | Italic text |

| **Ctrl+/** | Show all shortcuts |



Press **Ctrl+/** anytime to see the full shortcuts guide!



## πŸ’‘ Tips



- Right-click documents in the sidebar for quick actions (rename, delete, favorite)

- AI tools work best with content > 100 words

- Auto-save runs every 30 seconds (configurable in Settings)

- Export to "Artifact" format for beautiful standalone HTML pages



Start writing your masterpiece! Delete this text and create something amazing! πŸ’™



---



*Built with love by Jean & Elysia* πŸ’ŽπŸ’`;

        this.editor.setContent(welcomeMessage);
        this.currentDoc = {
            title: "Welcome to Elysia Markdown Studio",
            content: welcomeMessage
        };

        document.getElementById("doc-title").value = this.currentDoc.title;
    }

    showKeyboardShortcuts() {
        const shortcuts = `# ⌨️ Keyboard Shortcuts - Elysia Markdown Studio



## Document Management

- **Ctrl+S** - Save current document

- **Ctrl+N** - Create new document

- **Ctrl+/** - Show this shortcuts guide



## Text Formatting

- **Ctrl+B** - **Bold** text

- **Ctrl+I** - *Italic* text



## Navigation

- **Tab** - Indent / Next field

- **Shift+Tab** - Outdent / Previous field

- **Ctrl+F** - Search in document (browser default)



## Pro Tips πŸ’‘

- Right-click documents for context menu

- Use toolbar buttons for advanced formatting (tables, links, images)

- Drag & drop images into editor (coming soon!)



---



Press **Esc** to close this guide and continue writing!`;

        // Create temporary modal
        const modal = document.createElement("div");
        modal.className = "modal active";
        modal.id = "modal-shortcuts";
        modal.innerHTML = `

            <div class="modal-content">

                <div class="modal-header">

                    <h2>⌨️ Keyboard Shortcuts</h2>

                    <button class="modal-close" onclick="this.closest('.modal').remove()">Γ—</button>

                </div>

                <div class="modal-body">

                    <div class="markdown-preview">${marked.parse(shortcuts)}</div>

                </div>

                <div class="modal-footer">

                    <button class="btn-primary" onclick="this.closest('.modal').remove()">Got it!</button>

                </div>

            </div>

        `;

        document.body.appendChild(modal);

        // Close on Esc
        const handleEsc = e => {
            if (e.key === "Escape") {
                modal.remove();
                document.removeEventListener("keydown", handleEsc);
            }
        };
        document.addEventListener("keydown", handleEsc);

        // Close on backdrop click
        modal.addEventListener("click", e => {
            if (e.target === modal) {
                modal.remove();
            }
        });
    }
}

// Create global app instance
const app = new App();
window.app = app; // Make accessible to other modules

// Initialize on DOM ready
document.addEventListener("DOMContentLoaded", () => {
    app.init();
});

export default app;