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

   ELYSIA MARKDOWN STUDIO v1.0 - AI Tools Module

   Elysia's AI-powered features

*/

import Utils from "./utils.js";
import API from "./api.js";
import DB from "./db.js";

const AITools = {
    isProcessing: false,

    init() {
        document.getElementById("btn-ai-tools").addEventListener("click", () => {
            Utils.modal.open("modal-ai-tools");
        });

        document.querySelectorAll(".ai-tool-card").forEach(card => {
            card.addEventListener("click", () => {
                const tool = card.getAttribute("data-tool");
                this.executeTool(tool);
            });
        });
    },

    async executeTool(tool) {
        if (this.isProcessing) {
            Utils.toast.warning("Please wait - Elysia is already working on something!");
            return;
        }

        Utils.modal.close("modal-ai-tools");
        this.isProcessing = true;

        // Show loading indicator
        const loadingToast = this.showLoadingState(tool);

        try {
            switch (tool) {
                case "summarize":
                    await this.summarize();
                    break;
                case "improve":
                    await this.improveWriting();
                    break;
                case "merge":
                    await this.mergeDocuments();
                    break;
                case "outline":
                    await this.extractOutline();
                    break;
                case "duplicates":
                    await this.findDuplicates();
                    break;
                case "organize":
                    await this.smartOrganize();
                    break;
            }
        } catch (err) {
            console.error(`AI tool ${tool} failed:`, err);

            // User-friendly error messages
            let errorMsg = "AI tool failed";
            if (err.message.includes("API key")) {
                errorMsg = "API key not configured. Please add it in Settings ⚙️";
            } else if (err.message.includes("network") || err.message.includes("fetch")) {
                errorMsg = "Network error. Check your connection and try again.";
            } else if (err.message.includes("rate limit")) {
                errorMsg = "Rate limit reached. Please wait a moment and try again.";
            } else {
                errorMsg = err.message || "AI tool failed. Please try again.";
            }

            Utils.toast.error(errorMsg, 5000);
        } finally {
            this.isProcessing = false;
            // Remove loading toast
            if (loadingToast) loadingToast.remove();
        }
    },

    showLoadingState(tool) {
        const messages = {
            summarize: "🧠 Elysia is reading and summarizing...",
            improve: "✨ Elysia is polishing your writing...",
            merge: "📚 Elysia is merging documents...",
            outline: "🎯 Elysia is extracting outline...",
            duplicates: "🔍 Elysia is analyzing duplicates...",
            organize: "🏷️ Elysia is organizing content..."
        };

        const toast = Utils.toast.show(messages[tool] || "🧠 Elysia is thinking...", "loading", 0); // 0 = no auto-close
        return toast;
    },

    async summarize() {
        const content = window.app?.editor.getContent();
        if (!content) {
            Utils.toast.warning("No content to summarize");
            return;
        }

        if (content.length < 100) {
            Utils.toast.warning("Content too short. Add at least 100 characters for better summary.");
            return;
        }

        const summary = await API.summarize(content);

        // Create new document with summary
        const doc = await DB.createDocument({
            title: `Summary of ${window.app?.currentDoc?.title || "Document"}`,
            content: summary
        });

        Utils.toast.success("Summary created!");
        window.app?.loadDocument(doc.id);
    },

    async improveWriting() {
        const content = window.app?.editor.getContent();
        if (!content) {
            Utils.toast.warning("No content to improve");
            return;
        }

        if (content.length < 50) {
            Utils.toast.warning("Content too short. Add at least 50 characters for improvement.");
            return;
        }

        // 🎲 Show style selection modal (VS-inspired)
        this.showImproveStyleModal(content);
    },

    // 🎲 VS-INSPIRED: Show style selection modal
    showImproveStyleModal(content) {
        // Add styles if not present
        if (!document.getElementById("improve-styles-css")) {
            const style = document.createElement("style");
            style.id = "improve-styles-css";
            style.textContent = `

                .improve-style-grid {

                    display: grid;

                    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));

                    gap: 12px;

                    margin: 20px 0;

                }

                .improve-style-card {

                    padding: 16px;

                    background: var(--bg-secondary);

                    border: 2px solid transparent;

                    border-radius: 12px;

                    cursor: pointer;

                    transition: all 0.2s ease;

                    text-align: center;

                }

                .improve-style-card:hover {

                    border-color: var(--accent);

                    transform: translateY(-2px);

                }

                .improve-style-card.selected {

                    border-color: var(--accent);

                    background: rgba(167, 139, 250, 0.15);

                }

                .improve-style-icon {

                    font-size: 28px;

                    margin-bottom: 8px;

                }

                .improve-style-name {

                    font-weight: 600;

                    margin-bottom: 4px;

                }

                .improve-style-desc {

                    font-size: 11px;

                    color: var(--text-muted);

                }

                .improve-results {

                    margin-top: 16px;

                    max-height: 400px;

                    overflow-y: auto;

                }

                .improve-result-card {

                    padding: 16px;

                    margin-bottom: 12px;

                    background: var(--bg-secondary);

                    border-radius: 10px;

                    border-left: 4px solid var(--accent);

                }

                .improve-result-header {

                    display: flex;

                    justify-content: space-between;

                    align-items: center;

                    margin-bottom: 10px;

                }

                .improve-result-preview {

                    font-size: 13px;

                    color: var(--text-secondary);

                    line-height: 1.6;

                    max-height: 150px;

                    overflow-y: auto;

                    padding: 10px;

                    background: var(--bg-tertiary);

                    border-radius: 6px;

                }

            `;
            document.head.appendChild(style);
        }

        const modal = document.createElement("div");
        modal.className = "modal active";
        modal.id = "modal-improve-styles";
        modal.innerHTML = `

            <div class="modal-content" style="max-width: 600px;">

                <div class="modal-header">

                    <h2>✨ Improve Writing — Choose Style</h2>

                    <button class="btn-icon" onclick="document.getElementById('modal-improve-styles').remove()">✕</button>

                </div>

                <div class="modal-body">

                    <p style="color: var(--text-secondary); margin-bottom: 16px;">

                        🎲 <strong>Verbalized Sampling:</strong> I'll generate 5 different styles and you choose your favorite!

                    </p>



                    <div class="improve-style-grid">

                        <div class="improve-style-card" data-style="concise">

                            <div class="improve-style-icon">📝</div>

                            <div class="improve-style-name">Concis</div>

                            <div class="improve-style-desc">Court et direct</div>

                        </div>

                        <div class="improve-style-card" data-style="creative">

                            <div class="improve-style-icon">🎨</div>

                            <div class="improve-style-name">Créatif</div>

                            <div class="improve-style-desc">Vivant et imagé</div>

                        </div>

                        <div class="improve-style-card" data-style="academic">

                            <div class="improve-style-icon">📚</div>

                            <div class="improve-style-name">Académique</div>

                            <div class="improve-style-desc">Formel et structuré</div>

                        </div>

                        <div class="improve-style-card" data-style="professional">

                            <div class="improve-style-icon">💼</div>

                            <div class="improve-style-name">Professionnel</div>

                            <div class="improve-style-desc">Business-friendly</div>

                        </div>

                        <div class="improve-style-card" data-style="engaging">

                            <div class="improve-style-icon">🔥</div>

                            <div class="improve-style-name">Engageant</div>

                            <div class="improve-style-desc">Capte l'attention</div>

                        </div>

                    </div>



                    <div id="improve-loading" style="display: none; text-align: center; padding: 20px;">

                        <p>✨ Elysia génère les 5 variantes...</p>

                        <div class="progress-bar" style="margin-top: 10px;"><div class="progress-fill" style="width: 0%"></div></div>

                    </div>



                    <div id="improve-results" class="improve-results" style="display: none;"></div>

                </div>

                <div class="modal-footer">

                    <button class="btn-secondary" onclick="document.getElementById('modal-improve-styles').remove()">Annuler</button>

                    <button class="btn-primary" id="btn-generate-all" onclick="AITools.generateAllStyles()">

                        🎲 Générer les 5 styles

                    </button>

                </div>

            </div>

        `;

        document.body.appendChild(modal);

        // Store content for later use
        this.pendingContent = content;

        // Add click handlers for style cards
        modal.querySelectorAll(".improve-style-card").forEach(card => {
            card.addEventListener("click", () => {
                modal.querySelectorAll(".improve-style-card").forEach(c => c.classList.remove("selected"));
                card.classList.add("selected");
            });
        });
    },

    // 🎲 Generate all 5 styles at once (VS approach)
    async generateAllStyles() {
        const content = this.pendingContent;
        if (!content) return;

        const loadingDiv = document.getElementById("improve-loading");
        const resultsDiv = document.getElementById("improve-results");
        const generateBtn = document.getElementById("btn-generate-all");

        loadingDiv.style.display = "block";
        generateBtn.disabled = true;
        generateBtn.textContent = "⏳ Génération en cours...";

        const styles = [
            { id: "concise", name: "📝 Concis", desc: "Version plus courte et directe, sans fioritures" },
            { id: "creative", name: "🎨 Créatif", desc: "Version vivante avec métaphores et images" },
            { id: "academic", name: "📚 Académique", desc: "Version formelle et bien structurée" },
            { id: "professional", name: "💼 Professionnel", desc: "Version adaptée au monde des affaires" },
            { id: "engaging", name: "🔥 Engageant", desc: "Version qui capte l'attention du lecteur" }
        ];

        const results = [];
        const progressFill = loadingDiv.querySelector(".progress-fill");

        for (let i = 0; i < styles.length; i++) {
            const style = styles[i];
            try {
                const improved = await API.improveWritingWithStyle(content, style.id);
                results.push({
                    style: style,
                    content: improved,
                    success: true
                });
            } catch (err) {
                results.push({
                    style: style,
                    content: null,
                    success: false,
                    error: err.message
                });
            }
            progressFill.style.width = `${((i + 1) / styles.length) * 100}%`;
        }

        // Display results
        loadingDiv.style.display = "none";
        resultsDiv.style.display = "block";
        generateBtn.style.display = "none";

        let html = "<h3 style='margin-bottom: 12px;'>🎲 Choisissez votre version préférée:</h3>";

        results.forEach((result, index) => {
            if (result.success) {
                const preview = result.content.substring(0, 300) + (result.content.length > 300 ? "..." : "");
                html += `

                    <div class="improve-result-card">

                        <div class="improve-result-header">

                            <strong>${result.style.name}</strong>

                            <button class="btn-small" onclick="AITools.applyImprovement(${index})">✅ Utiliser</button>

                        </div>

                        <div class="improve-result-preview">${preview}</div>

                    </div>

                `;
            } else {
                html += `

                    <div class="improve-result-card" style="border-left-color: var(--error);">

                        <strong>${result.style.name}</strong>

                        <p style="color: var(--error);">Erreur: ${result.error}</p>

                    </div>

                `;
            }
        });

        resultsDiv.innerHTML = html;
        this.improveResults = results;
    },

    // Apply selected improvement
    async applyImprovement(index) {
        const result = this.improveResults?.[index];
        if (!result || !result.success) return;

        const replace = confirm("Remplacer le contenu actuel avec cette version?\n\n" + "OK = Remplacer | Annuler = Créer nouveau document");

        if (replace) {
            window.app?.editor.setContent(result.content);
            Utils.toast.success(`✨ Style "${result.style.name}" appliqué!`);
        } else {
            const doc = await DB.createDocument({
                title: `${result.style.name.replace(/[^\w\s]/g, "").trim()}: ${window.app?.currentDoc?.title || "Document"}`,
                content: result.content
            });
            Utils.toast.success("Nouveau document créé avec ce style!");
            window.app?.loadDocument(doc.id);
        }

        document.getElementById("modal-improve-styles")?.remove();
    },

    async mergeDocuments() {
        const docs = await DB.getAllDocuments();

        if (docs.length < 2) {
            Utils.toast.warning("Need at least 2 documents to merge");
            return;
        }

        // Simple selection (can be improved with checkboxes)
        const count = prompt(`How many recent documents to merge? (2-${Math.min(docs.length, 10)})`);
        if (!count || isNaN(count)) return;

        const selectedDocs = docs.slice(0, parseInt(count));

        const merged = await API.mergeDocuments(selectedDocs);

        // Create new merged document
        const doc = await DB.createDocument({
            title: "Merged Document",
            content: merged
        });

        Utils.toast.success("Documents merged!");
        window.app?.loadDocument(doc.id);
    },

    async extractOutline() {
        const content = window.app?.editor.getContent();
        if (!content) {
            Utils.toast.warning("No content to analyze");
            return;
        }

        const outline = await API.extractOutline(content);

        // Create new document with outline
        const doc = await DB.createDocument({
            title: `Outline of ${window.app?.currentDoc?.title || "Document"}`,
            content: outline
        });

        Utils.toast.success("Outline extracted!");
        window.app?.loadDocument(doc.id);
    },

    async findDuplicates() {
        const docs = await DB.getAllDocuments();

        if (docs.length < 2) {
            Utils.toast.warning("Need at least 2 documents");
            return;
        }

        Utils.toast.info("🔍 Finding duplicates...");

        const result = await API.findDuplicates(docs);

        // Show result in alert (can be improved with modal)
        alert(`Duplicate Analysis:\n\n${result}`);
    },

    async smartOrganize() {
        const content = window.app?.editor.getContent();
        if (!content) {
            Utils.toast.warning("No content to analyze");
            return;
        }

        Utils.toast.info("🏷️ Analyzing content...");

        const tags = await API.suggestTags(content);

        // Update current document with suggested tags
        if (window.app?.currentDoc) {
            window.app.currentDoc.tags = tags;
            await DB.updateDocument(window.app.currentDoc.id, { tags });

            Utils.toast.success(`Tags suggested: ${tags.join(", ")}`);
        }
    }
};

export default AITools;