<div class="box">
    <h1>My Notes</h1>
    <?php $this->renderFeedbackMessages(); ?>

    <div style="display: flex; gap: 20px; margin-top: 20px;">
        <!-- Notes Sidebar -->
        <div style="width: 300px;" class="notes-sidebar">
            <div style="padding: 15px; background: #f5f5f5; border: 1px solid #ddd; margin-bottom: 20px;">
                <form action="<?= Config::get('URL') ?>note/create" method="post" id="create-note-form" style="margin-bottom: 15px;">
                    <textarea name="note_text" placeholder="Write your note here..." style="width: 100%; max-width: 250px; padding: 8px; border: 1px solid #ddd; height: 80px; resize: vertical; margin-bottom: 10px;" required></textarea>
                    <button type="submit" class="button">Create Note</button>
                </form>
            </div>

            <div style="padding: 15px; background: #f5f5f5; border: 1px solid #ddd;">
                <h3 style="margin: 0 0 15px 0;">Your Notes</h3>
                <?php if ($this->notes): ?>
                    <?php foreach ($this->notes as $note): ?>
                        <div onclick="viewNote(<?= $note->note_id ?>)" style="padding: 12px; background: white; border: 1px solid #ddd; margin-bottom: 8px; cursor: pointer; transition: background-color 0.2s;" onmouseover="this.style.backgroundColor='#f0f0f0'" onmouseout="this.style.backgroundColor='white'">
                            <div style="font-weight: bold; margin-bottom: 5px; word-wrap: break-word;">
                                <?= htmlspecialchars(substr($note->note_text, 0, 50)) ?><?= strlen($note->note_text) > 50 ? '...' : '' ?>
                            </div>
                            <div style="font-size: 12px; color: #666; margin-bottom: 8px;">
                                <?= date('M j, Y H:i', strtotime($note->note_timestamp)) ?>
                            </div>
                            <div style="font-size: 11px; color: #999; font-style: italic; word-wrap: break-word;">
                                <?= htmlspecialchars(substr(strip_tags($note->note_text), 0, 80)) ?><?= strlen(strip_tags($note->note_text)) > 80 ? '...' : '' ?>
                            </div>
                            <div style="display: flex; gap: 8px; margin-top: 8px;" onclick="event.stopPropagation()">
                                <a onclick="editNote(<?= $note->note_id ?>)" style="font-size: 12px; padding: 4px 8px; background: #4CAF50; color: white; text-decoration: none; border-radius: 3px;">Edit</a>
                                <a href="<?= Config::get('URL') ?>note/delete/<?= $note->note_id ?>" style="font-size: 12px; padding: 4px 8px; background: #f44336; color: white; text-decoration: none; border-radius: 3px;" onclick="return confirm('Are you sure you want to delete this note?');">Delete</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p style="text-align: center; padding: 20px; background: white; border: 1px solid #ddd;">No notes yet. Create your first note!</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Notes Main Content -->
        <div style="flex: 1; border: 1px solid #ddd; background: white;" class="note-main-content">
            <div id="note-content" style="padding: 20px;">
                <div style="text-align: center; padding: 60px 20px; color: #666; background: #f9f9f9;">
                    <h3>Note Viewer</h3>
                    <p>Select a note from the left to view its contents</p>
                    <small style="color: #999;">Click anywhere on a note card to view it</small>
                </div>
            </div>
            
            <!-- Edit Note Form (Hidden by default) -->
            <div id="note-edit-form" style="display: none; padding: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #ddd;">
                    <h3 style="margin: 0;">Editing Note</h3>
                    <div style="display: flex; gap: 8px;">
                        <button onclick="cancelEdit()" class="button" style="background: #757575; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Cancel</button>
                        <button onclick="saveEdit()" class="button" style="background: #4CAF50; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Save Changes</button>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: bold; color: #333;">
                        Note Content (Markdown supported):
                    </label>
                    <textarea id="edit-note-text" style="width: 95%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 14px; line-height: 1.5; resize: vertical; min-height: 300px;" placeholder="Write your note here...

Markdown syntax supported:
# Header
**Bold** *italic* `code`
- List item
[Link](url)
> Quote"></textarea>
                </div>
                
                <div style="margin-top: 20px; padding: 15px; background: #f5f5f5; border-radius: 4px;">
                    <h4 style="margin: 0 0 10px 0; color: #333;">Preview:</h4>
                    <div id="edit-preview" style="padding: 15px; background: white; border: 1px solid #ddd; border-radius: 4px; min-height: 100px; font-size: 14px; line-height: 1.6;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentNoteId = null;
let isEditMode = false;

function viewNote(noteId) {
    if (currentNoteId === noteId && !isEditMode) return; // Don't reload if same note and not in edit mode
    
    currentNoteId = noteId;
    isEditMode = false;
    
    // Show view mode
    document.getElementById('note-content').style.display = 'block';
    document.getElementById('note-edit-form').style.display = 'none';
    
    // Show loading state
    const contentDiv = document.getElementById('note-content');
    contentDiv.innerHTML = `
        <div style="text-align: center; padding: 40px;">
            <div style="display: inline-block; padding: 10px; background: #f0f0f0; border-radius: 4px;">
                Loading note...
            </div>
        </div>
    `;
    
    // Load note via AJAX
    fetch(`<?= Config::get('URL') ?>note/getNote/${noteId}`)
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                const note = data.note;
                
                contentDiv.innerHTML = `
                    <div style="padding-bottom: 15px; border-bottom: 1px solid #ddd; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="margin: 0; color: #333;">Note</h3>
                            <small style="color: #666;">
                                Created: ${new Date(note.note_timestamp).toLocaleString('en-US', {
                                    month: 'short',
                                    day: 'numeric',
                                    year: 'numeric',
                                    hour: '2-digit',
                                    minute: '2-digit'
                                })}
                            </small>
                        </div>
                        <div style="display: flex; gap: 8px;">
                            <button onclick="editNote(${note.note_id})" style="padding: 8px 12px; background: #2196F3; color: white; border: none; border-radius: 4px; font-size: 12px; cursor: pointer;">Edit</button>
                            <a href="<?= Config::get('URL') ?>note/delete/${note.note_id}" style="padding: 8px 12px; background: #f44336; color: white; text-decoration: none; border-radius: 4px; font-size: 12px;" onclick="return confirm('Are you sure you want to delete this note?');">Delete</a>
                        </div>
                    </div>
                    <div style="white-space: pre-wrap; word-wrap: break-word; line-height: 1.6; font-size: 14px; color: #333;">
                        ${note.note_html}
                    </div>
                    ${note.note_text.length > 100 ? `
                        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee; font-size: 12px; color: #666;">
                            <i class="fa fa-file-text-o"></i> ${note.note_text.length} characters
                        </div>
                    ` : ''}
                `;
                
                // Highlight the active note in the sidebar
                document.querySelectorAll('.notes-sidebar .note-card').forEach(card => {
                    card.style.backgroundColor = card.dataset.noteId == noteId ? '#e8f4fd' : 'white';
                    card.style.borderColor = card.dataset.noteId == noteId ? '#2196F3' : '#ddd';
                });
                
            } else {
                contentDiv.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #f44336;">
                        <div style="font-size: 48px; margin-bottom: 10px;">⚠️</div>
                        <h4>Error loading note</h4>
                        <p>${data.message || 'Note not found'}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error loading note:', error);
            contentDiv.innerHTML = `
                <div style="text-align: center; padding: 40px; color: #f44336;">
                    <div style="font-size: 48px; margin-bottom: 10px;">❌</div>
                    <h4>Network Error</h4>
                    <p>Could not load note. Please try again.</p>
                </div>
            `;
        });
}

function editNote(noteId) {
    isEditMode = true;
    
    // Hide view mode, show edit form
    document.getElementById('note-content').style.display = 'none';
    document.getElementById('note-edit-form').style.display = 'block';
    
    // Load the note content
    fetch(`<?= Config::get('URL') ?>note/getNote/${noteId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const note = data.note;
                const textarea = document.getElementById('edit-note-text');
                const preview = document.getElementById('edit-preview');
                
                textarea.value = note.note_text;
                preview.innerHTML = note.note_html;
                
                // Setup live preview
                textarea.oninput = function() {
                    preview.innerHTML = SimpleMarkdown.parse(this.value);
                };
            }
        })
        .catch(error => {
            console.error('Error loading note for editing:', error);
            alert('Error loading note for editing');
        });
}

function cancelEdit() {
    isEditMode = false;
    document.getElementById('note-content').style.display = 'block';
    document.getElementById('note-edit-form').style.display = 'none';
    viewNote(currentNoteId);
}

function saveEdit() {
    const textarea = document.getElementById('edit-note-text');
    const noteText = textarea.value;
    
    if (!noteText.trim()) {
        alert('Note content cannot be empty');
        return;
    }
    
    const saveButton = document.querySelector('button[onclick="saveEdit()"]');
    const originalText = saveButton.textContent;
    saveButton.textContent = 'Saving...';
    saveButton.disabled = true;
    
    fetch(`<?= Config::get('URL') ?>note/editSave`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            note_id: currentNoteId,
            note_text: noteText
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showFeedback('Note saved successfully!', 'success');
            isEditMode = false;
            document.getElementById('note-content').style.display = 'block';
            document.getElementById('note-edit-form').style.display = 'none';
            viewNote(currentNoteId); // Reload the note view
            
            // Refresh the notes list to show the updated preview
            setTimeout(() => {
                refreshNotesList();
            }, 500);
        } else {
            showFeedback(data.message || 'Failed to save note', 'error');
        }
    })
    .catch(error => {
        console.error('Error saving note:', error);
        showFeedback('Network error. Please try again.', 'error');
    })
    .finally(() => {
        saveButton.textContent = originalText;
        saveButton.disabled = false;
    });
}

// Simple markdown parser for browser use
class SimpleMarkdown {
    static parse(text) {
        text = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        
        // Headers
        text = text.replace(/^#{1,6}\s+(.+)$/gm, '<h3>$1</h3>');
        
        // Bold
        text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
        
        // Italic
        text = text.replace(/\*(.+?)\*/g, '<em>$1</em>');
        
        // Code
        text = text.replace(/`(.+?)`/g, '<code>$1</code>');
        
        // Code blocks
        text = text.replace(/```(.+?)```/gs, '<pre><code>$1</code></pre>');
        
        // Links
        text = text.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2" target="_blank">$1</a>');
        
        // Blockquotes
        text = text.replace(/^>\s+(.+)$/gm, '<blockquote>$1</blockquote>');
        
        // Lists
        text = text.replace(/^\-\s+(.+)$/gm, '<li>$1</li>');
        text = text.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
        
        // Line breaks
        text = text.replace(/\n/g, '<br>');
        
        return text;
    }
}

// Add note IDs to sidebar cards for highlighting
document.addEventListener('DOMContentLoaded', function() {
    // Handle note creation form submission
    const createForm = document.getElementById('create-note-form');
    if (createForm) {
        createForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const noteText = this.note_text.value;
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            
            if (!noteText.trim()) {
                alert('Please enter a note');
                return;
            }
            
            // Show loading state
            submitButton.textContent = 'Creating...';
            submitButton.disabled = true;
            
            fetch(`<?= Config::get('URL') ?>note/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: new URLSearchParams({ note_text: noteText })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Clear form
                    this.reset();
                    
                    // Show success message
                    showFeedback('Note created successfully!', 'success');
                    
                    // Refresh notes list after a short delay
                    setTimeout(() => {
                        refreshNotesList();
                    }, 500);
                    
                } else {
                    showFeedback(data.message || 'Failed to create note', 'error');
                }
            })
            .catch(error => {
                console.error('Error creating note:', error);
                showFeedback('Network error. Please try again.', 'error');
            })
            .finally(() => {
                // Restore button state
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    }
    
    // Add note IDs to sidebar cards for highlighting
    const noteCards = document.querySelectorAll('.notes-sidebar > div:nth-child(2) > div');
    noteCards.forEach((card, index) => {
        // Skip the "Your Notes" header and the form
        if (card.querySelector('a[href*="note/edit"]')) {
            const editLink = card.querySelector('a[href*="note/edit"]');
            const noteId = editLink.href.split('/').pop();
            card.classList.add('note-card');
            card.dataset.noteId = noteId;
            card.style.cursor = 'pointer';
        }
    });
});

function refreshNotesList() {
    // Reload the page to refresh the notes list
    // This is simpler than trying to rebuild the sidebar via AJAX
    window.location.reload();
}

function showFeedback(message, type) {
    // Create feedback element
    const feedback = document.createElement('div');
    feedback.className = `feedback-${type}`;
    feedback.textContent = message;
    feedback.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        background: ${type === 'success' ? '#4caf50' : '#f44336'};
        color: white;
        border-radius: 4px;
        z-index: 1000;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        animation: slideIn 0.3s ease;
    `;

    document.body.appendChild(feedback);

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

// Add CSS for animations
const animationStyle = document.createElement('style');
animationStyle.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
    
    .feedback-success {
        background: linear-gradient(135deg, #4caf50, #45a049) !important;
    }
    
    .feedback-error {
        background: linear-gradient(135deg, #f44336, #d32f2f) !important;
    }
`;
document.head.appendChild(animationStyle);

// Add some CSS for better styling
const style = document.createElement('style');
style.textContent = `
    .note-card {
        transition: all 0.2s ease;
        position: relative;
    }
    
    .note-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    .note-card:active {
        transform: translateY(0);
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .note-main-content {
        min-height: 500px;
    }
    
    @media (max-width: 768px) {
        .note-main-content {
            margin-top: 20px;
        }
    }
`;
document.head.appendChild(style);
</script>
