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
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
// AI Notes Application
class AINotesApp {
    constructor() {
        this.notes = JSON.parse(localStorage.getItem('aiNotes') || '[]');
        this.currentNote = null;
        this.apiKey = localStorage.getItem('openrouterApiKey') || '';
        this.selectedModel = localStorage.getItem('selectedModel') || '';
        this.models = [];
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.renderNotesList();
        this.loadSettings();
        this.fetchModels();
        this.createNewNote();
    }

    setupEventListeners() {
        // Header buttons
        document.getElementById('settingsBtn').addEventListener('click', () => this.showSettings());
        document.getElementById('newNoteBtn').addEventListener('click', () => this.createNewNote());
        
        // Note title and content
        document.getElementById('noteTitle').addEventListener('input', () => this.saveCurrentNote());
        document.getElementById('noteContent').addEventListener('input', () => this.handleContentChange());
        
        // AI Dialog
        document.getElementById('closeAiDialog').addEventListener('click', () => this.hideAiDialog());
        document.getElementById('sendBtn').addEventListener('click', () => this.sendAiMessage());
        document.getElementById('aiMessage').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendAiMessage();
        });
        
        // Settings modal
        document.getElementById('closeSettings').addEventListener('click', () => this.hideSettings());
        document.getElementById('saveSettings').addEventListener('click', () => this.saveSettings());
        
        // Global key listeners
        document.addEventListener('keydown', (e) => this.handleKeydown(e));
        
        // Auto-save
        setInterval(() => this.saveCurrentNote(), 30000);
    }

    handleKeydown(e) {
        // Space bar at line start triggers AI dialog
        if (e.key === ' ' && e.target.id === 'noteContent') {
            const cursorPos = e.target.selectionStart;
            const text = e.target.value;
            
            // Check if cursor is at the start of a line
            const lineStart = text.lastIndexOf('\n', cursorPos - 1) + 1;
            const isLineStart = cursorPos === lineStart || (cursorPos === 0 && text.length === 0);
            
            if (isLineStart) {
                e.preventDefault();
                this.showAiDialog();
            }
        }
        
        // Escape closes dialogs
        if (e.key === 'Escape') {
            this.hideAiDialog();
            this.hideSettings();
        }
    }

    handleContentChange() {
        // Add visual indicator when at line start
        const textarea = document.getElementById('noteContent');
        const cursorPos = textarea.selectionStart;
        const text = textarea.value;
        
        // This will be handled by the keydown event for space bar
    }

    showAiDialog() {
        const dialog = document.getElementById('aiDialog');
        dialog.classList.remove('hidden');
        dialog.classList.add('ai-dialog-enter');
        
        // Fill in current settings
        const apiKeyInput = document.getElementById('apiKeyInput');
        const modelSelect = document.getElementById('modelSelect');
        
        if (this.apiKey) apiKeyInput.value = this.apiKey;
        if (this.selectedModel) modelSelect.value = this.selectedModel;
        
        // Focus on message input
        setTimeout(() => {
            document.getElementById('aiMessage').focus();
        }, 100);
    }

    hideAiDialog() {
        const dialog = document.getElementById('aiDialog');
        dialog.classList.add('ai-dialog-exit');
        setTimeout(() => {
            dialog.classList.add('hidden');
            dialog.classList.remove('ai-dialog-exit');
            document.getElementById('aiMessage').value = '';
            document.getElementById('aiResponse').classList.add('hidden');
        }, 300);
    }

    async sendAiMessage() {
        const message = document.getElementById('aiMessage').value.trim();
        const apiKey = document.getElementById('apiKeyInput').value.trim() || this.apiKey;
        const model = document.getElementById('modelSelect').value.trim() || this.selectedModel;
        
        if (!message) return;
        if (!apiKey) {
            alert('请输入 API Key');
            return;
        }
        if (!model) {
            alert('请选择模型');
            return;
        }
        
        // Update global settings
        this.apiKey = apiKey;
        this.selectedModel = model;
        localStorage.setItem('openrouterApiKey', apiKey);
        localStorage.setItem('selectedModel', model);
        
        const sendBtn = document.getElementById('sendBtn');
        const responseDiv = document.getElementById('aiResponse');
        
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<div class="typing-indicator"></div>';
        responseDiv.classList.remove('hidden');
        responseDiv.innerHTML = '<div class="typing-indicators"><div class="typing-indicator"></div><div class="typing-indicator"></div><div class="typing-indicator"></div></div>';
        
        try {
            const response = await this.callOpenRouter(apiKey, model, message);
            await this.streamResponse(response, responseDiv);
            
            // Convert markdown to HTML and insert into editor
            const markdownHtml = marked.parse(response);
            this.insertMarkdownIntoEditor(markdownHtml);
            
        } catch (error) {
            responseDiv.innerHTML = `<div class="text-red-500">错误: ${error.message}</div>`;
        } finally {
            sendBtn.disabled = false;
            sendBtn.innerHTML = '<i data-feather="send" class="w-4 h-4"></i>';
            feather.replace();
        }
    }

    async callOpenRouter(apiKey, model, message) {
        const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'HTTP-Referer': window.location.origin,
                'X-Title': 'AI Notes'
            },
            body: JSON.stringify({
                model: model,
                messages: [
                    {
                        role: 'user',
                        content: message
                    }
                ],
                stream: true
            })
        });
        
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.error?.message || `HTTP ${response.status}`);
        }
        
        return response;
    }

    async streamResponse(response, responseDiv) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let fullResponse = '';
        
        responseDiv.innerHTML = '';
        
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            
            const chunk = decoder.decode(value, { stream: true });
            const lines = chunk.split('\n').filter(line => line.trim());
            
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const data = line.slice(6);
                    if (data === '[DONE]') continue;
                    
                    try {
                        const parsed = JSON.parse(data);
                        const content = parsed.choices?.[0]?.delta?.content;
                        if (content) {
                            fullResponse += content;
                            responseDiv.innerHTML = `<div class="markdown-content">${marked.parse(fullResponse)}</div>`;
                        }
                    } catch (e) {
                        // Ignore parsing errors for keep-alive lines
                    }
                }
            }
        }
        
        return fullResponse;
    }

    insertMarkdownIntoEditor(htmlContent) {
        const textarea = document.getElementById('noteContent');
        const cursorPos = textarea.selectionStart;
        const text = textarea.value;
        
        // Find the start of the current line
        const lineStart = text.lastIndexOf('\n', cursorPos - 1) + 1;
        
        // Insert a newline and the AI response
        const insertText = `\n\n${htmlContent}\n`;
        const newText = text.substring(0, lineStart) + insertText + text.substring(cursorPos);
        
        textarea.value = newText;
        
        // Set cursor position after the inserted content
        const newCursorPos = lineStart + insertText.length;
        textarea.setSelectionRange(newCursorPos, newCursorPos);
        textarea.focus();
        
        this.saveCurrentNote();
    }

    async fetchModels() {
        if (!this.apiKey) return;
        
        try {
            const response = await fetch('https://openrouter.ai/api/v1/models', {
                headers: {
                    'Authorization': `Bearer ${this.apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.ok) {
                const data = await response.json();
                this.models = data.data || [];
                this.populateModelSelects();
            }
        } catch (error) {
            console.warn('Failed to fetch models:', error);
        }
    }

    populateModelSelects() {
        const modelSelects = ['modelSelect', 'globalModelSelect'];
        
        modelSelects.forEach(selectId => {
            const select = document.getElementById(selectId);
            if (!select) return;
            
            // Clear existing options except the first one
            while (select.children.length > 1) {
                select.removeChild(select.lastChild);
            }
            
            // Add model options
            this.models.forEach(model => {
                const option = document.createElement('option');
                option.value = model.id;
                option.textContent = model.name || model.id;
                if (model.id === this.selectedModel) {
                    option.selected = true;
                }
                select.appendChild(option);
            });
        });
    }

    createNewNote() {
        const newNote = {
            id: Date.now(),
            title: '无标题笔记',
            content: '',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        this.notes.unshift(newNote);
        this.currentNote = newNote;
        this.loadNoteToEditor(newNote);
        this.renderNotesList();
        this.saveNotes();
    }

    loadNoteToEditor(note) {
        document.getElementById('noteTitle').value = note.title;
        document.getElementById('noteContent').value = note.content;
    }

    saveCurrentNote() {
        if (!this.currentNote) return;
        
        this.currentNote.title = document.getElementById('noteTitle').value || '无标题笔记';
        this.currentNote.content = document.getElementById('noteContent').value;
        this.currentNote.updatedAt = new Date().toISOString();
        
        // Update in notes array
        const index = this.notes.findIndex(note => note.id === this.currentNote.id);
        if (index !== -1) {
            this.notes[index] = this.currentNote;
        }
        
        this.saveNotes();
        this.renderNotesList();
    }

    loadNote(note) {
        this.currentNote = note;
        this.loadNoteToEditor(note);
    }

    deleteNote(noteId) {
        if (confirm('确定要删除这个笔记吗?')) {
            this.notes = this.notes.filter(note => note.id !== noteId);
            
            if (this.currentNote?.id === noteId) {
                this.createNewNote();
            }
            
            this.saveNotes();
            this.renderNotesList();
        }
    }

    saveNotes() {
        localStorage.setItem('aiNotes', JSON.stringify(this.notes));
    }

    renderNotesList() {
        const notesList = document.getElementById('notesList');
        
        if (this.notes.length === 0) {
            notesList.innerHTML = `
                <div class="col-span-full text-center py-12">
                    <i data-feather="file-text" class="w-12 h-12 text-gray-300 mx-auto mb-4"></i>
                    <p class="text-gray-500">还没有笔记,开始创建你的第一个笔记吧!</p>
                </div>
            `;
            feather.replace();
            return;
        }
        
        notesList.innerHTML = this.notes.map(note => `
            <div class="note-card bg-white rounded-xl p-4 border border-gray-200 cursor-pointer" onclick="app.loadNote(${note.id})">
                <div class="flex items-start justify-between mb-3">
                    <h3 class="font-medium text-gray-800 truncate pr-2">${this.escapeHtml(note.title)}</h3>
                    <button onclick="event.stopPropagation(); app.deleteNote(${note.id})" class="text-gray-400 hover:text-red-500 transition-colors">
                        <i data-feather="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>
                <p class="text-sm text-gray-600 line-clamp-3 mb-3">${this.escapeHtml(note.content.substring(0, 100))}${note.content.length > 100 ? '...' : ''}</p>
                <div class="text-xs text-gray-400">
                    ${new Date(note.updatedAt).toLocaleDateString('zh-CN')}
                </div>
            </div>
        `).join('');
        
        feather.replace();
    }

    showSettings() {
        document.getElementById('settingsModal').classList.remove('hidden');
        document.getElementById('globalApiKey').value = this.apiKey;
        document.getElementById('globalModelSelect').value = this.selectedModel;
    }

    hideSettings() {
        document.getElementById('settingsModal').classList.add('hidden');
    }

    saveSettings() {
        this.apiKey = document.getElementById('globalApiKey').value.trim();
        this.selectedModel = document.getElementById('globalModelSelect').value;
        
        localStorage.setItem('openrouterApiKey', this.apiKey);
        localStorage.setItem('selectedModel', this.selectedModel);
        
        if (this.apiKey) {
            this.fetchModels();
        }
        
        this.hideSettings();
        
        // Update the AI dialog if it's open
        if (!document.getElementById('aiDialog').classList.contains('hidden')) {
            document.getElementById('apiKeyInput').value = this.apiKey;
            document.getElementById('modelSelect').value = this.selectedModel;
        }
    }

    loadSettings() {
        // This is handled in the constructor, but we can refresh the UI
        if (this.apiKey) {
            this.fetchModels();
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize the app
const app = new AINotesApp();