{% extends "layout.html" %}

{% block content %}
<div class="timetrack-container note-editor-container">
    <div class="editor-header">
        <h2>{% if note %}Edit: {{ note.title }}{% else %}New Note{% endif %}</h2>
        <div class="editor-actions">
            <button type="button" class="btn-icon settings-btn" id="settings-toggle" title="Settings">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="12" cy="12" r="1"></circle>
                    <circle cx="12" cy="5" r="1"></circle>
                    <circle cx="12" cy="19" r="1"></circle>
                </svg>
            </button>
        </div>
    </div>

    <!-- Settings dropdown menu -->
    <div class="settings-dropdown" id="settings-dropdown">
        <div class="settings-content">
            <h3>Note Settings</h3>
            
            <div class="settings-group">
                <label for="visibility">Visibility</label>
                <select id="visibility" name="visibility" class="form-control" required>
                    <option value="Private" {% if not note or note.visibility.value == 'Private' %}selected{% endif %}>
                        🔒 Private - Only you can see this
                    </option>
                    <option value="Team" {% if note and note.visibility.value == 'Team' %}selected{% endif %}>
                        👥 Team - Your team members can see this
                    </option>
                    <option value="Company" {% if note and note.visibility.value == 'Company' %}selected{% endif %}>
                        🏢 Company - Everyone in your company can see this
                    </option>
                </select>
            </div>

            <div class="settings-group">
                <label for="project_id">Project (Optional)</label>
                <select id="project_id" name="project_id" class="form-control">
                    <option value="">No project</option>
                    {% for project in projects %}
                    <option value="{{ project.id }}" {% if note and note.project_id == project.id %}selected{% endif %}>
                        {{ project.code }} - {{ project.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="settings-group">
                <label for="task_id">Task (Optional)</label>
                <select id="task_id" name="task_id" class="form-control">
                    <option value="">No task</option>
                    {% for task in tasks %}
                    <option value="{{ task.id }}" {% if note and note.task_id == task.id %}selected{% endif %}>
                        #{{ task.id }} - {{ task.title }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            <div class="settings-group">
                <label for="folder">Folder</label>
                <input type="text" id="folder" name="folder" class="form-control" 
                       placeholder="e.g., Work/Projects or Personal"
                       value="{{ note.folder if note and note.folder else '' }}"
                       list="folder-suggestions">
                <datalist id="folder-suggestions">
                    {% for folder in all_folders %}
                    <option value="{{ folder }}">
                    {% endfor %}
                </datalist>
            </div>
            
            <div class="settings-group">
                <label for="tags">Tags (comma-separated)</label>
                <input type="text" id="tags" name="tags" class="form-control" 
                       placeholder="documentation, meeting-notes, technical"
                       value="{{ note.tags if note and note.tags else '' }}">
            </div>
        </div>
    </div>

    <form method="POST" id="note-form">
        <div class="editor-layout">
            <!-- Editor Panel -->
            <div class="editor-panel">
                <input type="hidden" id="title" name="title" value="{{ note.title if note else '' }}" required>
                
                <div class="form-group editor-group">
                    <div class="editor-toolbar">
                        <button type="button" class="toolbar-btn toolbar-bold" onclick="insertMarkdown('**', '**')" title="Bold">
                            <b>B</b>
                        </button>
                        <button type="button" class="toolbar-btn toolbar-italic" onclick="insertMarkdown('*', '*')" title="Italic">
                            <i>I</i>
                        </button>
                        <button type="button" class="toolbar-btn toolbar-code" onclick="insertMarkdown('`', '`')" title="Inline Code">
                            &lt;/&gt;
                        </button>
                        <button type="button" class="toolbar-btn toolbar-code-block" onclick="insertMarkdown('```\\n', '\\n```')" title="Code Block">
                            [&nbsp;]
                        </button>
                        <span class="toolbar-separator"></span>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('# ', '')" title="Heading 1">
                            H1
                        </button>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('## ', '')" title="Heading 2">
                            H2
                        </button>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('### ', '')" title="Heading 3">
                            H3
                        </button>
                        <span class="toolbar-separator"></span>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('- ', '')" title="Bullet List">
                            ≡
                        </button>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('1. ', '')" title="Numbered List">
                            ≣
                        </button>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('> ', '')" title="Quote">
                            ❞
                        </button>
                        <span class="toolbar-separator"></span>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('[', '](url)')" title="Link">
                            🔗
                        </button>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('![', '](url)')" title="Image">
                            🖼
                        </button>
                        <button type="button" class="toolbar-btn" onclick="insertMarkdown('---\\n', '')" title="Horizontal Rule">
                            —
                        </button>
                    </div>
                    <div id="ace-editor" class="ace-editor-container">{{ note.content if note else '' }}</div>
                    <textarea id="content" name="content" class="form-control markdown-editor" 
                              style="display: none;" required>{{ note.content if note else '' }}</textarea>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        {% if note %}Update Note{% else %}Create Note{% endif %}
                    </button>
                    <a href="{{ url_for('notes_list') }}" class="btn btn-secondary">Cancel</a>
                </div>
            </div>

            <!-- Preview Panel -->
            <div class="preview-panel" id="preview-panel">
                <div class="preview-header">
                    <h3>Preview</h3>
                    <button type="button" class="btn-icon collapse-btn" id="preview-toggle" title="Toggle Preview">
                        <span class="collapse-icon">&lt;&lt;</span>
                    </button>
                </div>
                <div id="preview-content" class="markdown-content">
                    <p class="preview-placeholder">Start typing to see the preview...</p>
                </div>
            </div>
        </div>
    </form>

    {% if note and note.linked_notes %}
    <div class="linked-notes-section">
        <h3>Linked Notes</h3>
        <div class="linked-notes-list">
            {% for link in note.linked_notes %}
            <div class="linked-note-item">
                <a href="{{ url_for('view_note', slug=link.target_note.slug) }}">
                    {{ link.target_note.title }}
                </a>
                <span class="link-type">{{ link.link_type }}</span>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}
</div>

<style>
/* Note editor specific styles */
.note-editor-container {
    max-width: none !important;
    width: 100% !important;
    padding: 1rem !important;
    margin: 0 !important;
}

.editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
    position: relative;
}

.editor-actions {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.btn-icon {
    width: 40px;
    height: 40px;
    border: 1px solid #dee2e6;
    background: white;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    padding: 0;
}

.btn-icon:hover {
    background: #f8f9fa;
    border-color: #adb5bd;
}

.btn-icon:active {
    background: #e9ecef;
}

.btn-icon svg {
    color: #666;
}

.settings-dropdown {
    position: fixed;
    width: 320px;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    z-index: 1000;
    display: none;
    max-height: 80vh;
    overflow-y: auto;
}

.settings-dropdown.show {
    display: block;
}

.settings-content {
    padding: 1.5rem;
}

.settings-content h3 {
    margin: 0 0 1.5rem 0;
    font-size: 1.1rem;
    color: #333;
}

.settings-group {
    margin-bottom: 1.25rem;
}

.settings-group:last-child {
    margin-bottom: 0;
}

.settings-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #555;
    font-size: 0.9rem;
}

.editor-layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    min-height: 600px;
    transition: grid-template-columns 0.3s ease;
}

.editor-layout.preview-collapsed {
    grid-template-columns: 1fr 60px;
}

.editor-panel, .preview-panel {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 1.5rem;
}

.preview-panel {
    background: #f8f9fa;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
}

.preview-panel.collapsed {
    cursor: pointer;
}

.preview-panel.collapsed .markdown-content {
    display: none;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.preview-header h3 {
    margin: 0;
    color: #666;
    transition: transform 0.3s ease;
}

.preview-panel.collapsed .preview-header {
    font-size: small;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) rotate(-90deg);
    width: max-content;
}

.preview-panel.collapsed .preview-header h3 {
    margin: 0;
}

.collapse-btn {
    transition: transform 0.3s ease;
    z-index: 10;
    position: relative;
}

.preview-panel.collapsed .collapse-btn {
    display: none;
}

.collapse-icon {
    font-size: 16px;
    font-weight: normal;
    font-family: monospace;
    display: inline-block;
    transition: transform 0.3s ease;
    line-height: 1;
    letter-spacing: -2px;
    color: #666;
}

.editor-layout.preview-collapsed .collapse-icon {
    transform: rotate(180deg);
}

.form-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #333;
}

.form-control {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e9ecef;
    border-radius: 6px;
    font-size: 1rem;
    transition: border-color 0.2s ease;
}

.form-control:focus {
    outline: none;
    border-color: #4CAF50;
    box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}

.editor-toolbar {
    display: flex;
    gap: 0.25rem;
    padding: 0.5rem;
    background: #f8f9fa;
    border: 2px solid #e9ecef;
    border-bottom: none;
    border-radius: 6px 6px 0 0;
    flex-wrap: wrap;
}

.toolbar-btn {
    padding: 0.5rem 0.75rem;
    min-width: 40px;
    border: 1px solid #dee2e6;
    background: white;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
    font-weight: 500;
    color: #333;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.toolbar-btn:hover {
    background: #e9ecef;
    border-color: #adb5bd;
    color: #000;
}

.toolbar-btn:active {
    background: #dee2e6;
    transform: translateY(1px);
}

/* Special styling for specific buttons */
.toolbar-bold {
    font-weight: bold;
}

.toolbar-italic {
    font-style: italic;
}

.toolbar-code, .toolbar-code-block {
    font-family: monospace;
}

/* Ensure button content is visible */
.toolbar-btn b, .toolbar-btn i {
    font-size: 1rem;
    line-height: 1;
}

.toolbar-separator {
    width: 1px;
    background: #dee2e6;
    margin: 0 0.5rem;
}

.markdown-editor {
    font-family: 'Monaco', 'Consolas', 'Courier New', monospace;
    font-size: 0.95rem;
    line-height: 1.5;
    border-radius: 0 0 6px 6px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
}

.ace-editor-container {
    width: 100%;
    height: 500px;
    border: 2px solid #e9ecef;
    border-radius: 0 0 6px 6px;
    border-top: none;
    font-size: 14px;
}

.markdown-content {
    padding: 1rem;
    min-height: 400px;
    max-height: 700px;
    overflow-y: auto;
}

.markdown-content h1, .markdown-content h2, .markdown-content h3,
.markdown-content h4, .markdown-content h5, .markdown-content h6 {
    margin-top: 1.5rem;
    margin-bottom: 1rem;
}

.markdown-content h1 { font-size: 2rem; }
.markdown-content h2 { font-size: 1.5rem; }
.markdown-content h3 { font-size: 1.25rem; }

.markdown-content p {
    margin-bottom: 1rem;
}

.markdown-content code {
    background: #e9ecef;
    padding: 0.2rem 0.4rem;
    border-radius: 3px;
    font-size: 0.9em;
}

.markdown-content pre {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 6px;
    overflow-x: auto;
    margin-bottom: 1rem;
}

.markdown-content pre code {
    background: none;
    padding: 0;
}

.markdown-content blockquote {
    border-left: 4px solid #dee2e6;
    padding-left: 1rem;
    margin: 1rem 0;
    color: #666;
}

.markdown-content ul, .markdown-content ol {
    margin-bottom: 1rem;
    padding-left: 2rem;
}

.markdown-content table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 1rem;
}

.markdown-content th, .markdown-content td {
    border: 1px solid #dee2e6;
    padding: 0.5rem;
}

.markdown-content th {
    background: #f8f9fa;
    font-weight: 600;
}

.preview-placeholder {
    color: #999;
    font-style: italic;
}

.form-actions {
    display: flex;
    gap: 1rem;
    margin-top: 2rem;
}

.linked-notes-section {
    margin-top: 2rem;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 8px;
}

.linked-notes-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    margin-top: 1rem;
}

.linked-note-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.5rem 1rem;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 4px;
}

.link-type {
    font-size: 0.85rem;
    color: #666;
    font-style: italic;
}

/* Form elements inside settings dropdown */
.settings-dropdown .form-control {
    font-size: 0.9rem;
    padding: 0.5rem 0.75rem;
}

/* Responsive design */
@media (max-width: 1024px) {
    .editor-layout {
        grid-template-columns: 1fr;
    }
    
    .editor-layout.preview-collapsed {
        grid-template-columns: 1fr;
    }
    
    .preview-panel {
        order: -1;
        min-height: 300px;
        max-height: 400px;
    }
    
    .preview-panel.collapsed {
        min-height: 60px;
        max-height: 60px;
    }
    
    .preview-panel.collapsed .preview-header {
        position: static;
        transform: none;
    }
    
    .preview-panel.collapsed .collapse-btn {
        display: flex;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .settings-dropdown {
        width: 300px;
    }
}
</style>

<!-- Load Ace Editor -->
<script src="{{ url_for('static', filename='js/ace/ace.js') }}"></script>
<script src="{{ url_for('static', filename='js/ace/mode-markdown.js') }}"></script>
<script src="{{ url_for('static', filename='js/ace/theme-github.js') }}"></script>
<script src="{{ url_for('static', filename='js/ace/theme-monokai.js') }}"></script>
<script src="{{ url_for('static', filename='js/ace/ext-language_tools.js') }}"></script>

<script>
// Global Ace Editor instance
let aceEditor;

// Markdown toolbar functions for Ace Editor
function insertMarkdown(before, after) {
    if (!aceEditor) return;
    
    const session = aceEditor.getSession();
    const selection = aceEditor.getSelection();
    const range = selection.getRange();
    const selectedText = session.getTextRange(range);
    
    if (selectedText) {
        // Replace selected text
        session.replace(range, before + selectedText + after);
        
        // Select the text between the markdown markers
        const newRange = selection.getRange();
        newRange.setStart(newRange.start.row, newRange.start.column + before.length);
        newRange.setEnd(newRange.start.row, newRange.start.column + selectedText.length);
        selection.setRange(newRange);
    } else {
        // Insert at cursor position
        const position = aceEditor.getCursorPosition();
        session.insert(position, before + after);
        
        // Move cursor between the markers
        aceEditor.moveCursorTo(position.row, position.column + before.length);
    }
    
    aceEditor.focus();
    syncContentAndUpdatePreview();
}

// Extract title from first line of content
function extractTitleFromContent(content) {
    const lines = content.split('\n');
    let firstLine = '';
    
    // Find the first non-empty line
    for (let line of lines) {
        const trimmed = line.trim();
        if (trimmed) {
            // Remove markdown headers if present
            firstLine = trimmed.replace(/^#+\s*/, '');
            break;
        }
    }
    
    // If no non-empty line found, use default
    return firstLine || 'Untitled Note';
}

// Sync Ace Editor content with hidden textarea and update preview
function syncContentAndUpdatePreview() {
    if (!aceEditor) return;
    
    const content = aceEditor.getValue();
    document.getElementById('content').value = content;
    
    // Update title from first line
    const title = extractTitleFromContent(content);
    document.getElementById('title').value = title;
    
    // Update the page header to show current title
    const headerTitle = document.querySelector('.editor-header h2');
    if (headerTitle) {
        const isEdit = headerTitle.textContent.includes('Edit');
        headerTitle.textContent = title ? (isEdit ? `Edit: ${title}` : title) : (isEdit ? 'Edit Note' : 'Create Note');
    }
    
    updatePreview();
}

// Live preview update
let previewTimer;
function updatePreview() {
    clearTimeout(previewTimer);
    previewTimer = setTimeout(() => {
        const content = document.getElementById('content').value;
        const preview = document.getElementById('preview-content');
        
        if (content.trim() === '') {
            preview.innerHTML = '<p class="preview-placeholder">Start typing to see the preview...</p>';
            return;
        }
        
        // Send content to server for markdown rendering
        fetch('/api/render-markdown', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content: content })
        })
        .then(response => response.json())
        .then(data => {
            if (data.html) {
                preview.innerHTML = data.html;
            }
        })
        .catch(error => {
            console.error('Error rendering markdown:', error);
        });
    }, 300);
}

// Initialize Ace Editor
function initializeAceEditor() {
    // Create Ace Editor instance
    aceEditor = ace.edit("ace-editor");
    
    // Set theme (use github theme for light mode)
    aceEditor.setTheme("ace/theme/github");
    
    // Set markdown mode
    aceEditor.session.setMode("ace/mode/markdown");
    
    // Configure editor options
    aceEditor.setOptions({
        fontSize: "14px",
        showPrintMargin: false,
        showGutter: true,
        highlightActiveLine: true,
        enableBasicAutocompletion: true,
        enableLiveAutocompletion: true,
        enableSnippets: true,
        tabSize: 2,
        useSoftTabs: true,
        wrap: true,
        showInvisibles: false,
        scrollPastEnd: 0.5
    });
    
    // Set initial content from hidden textarea
    const initialContent = document.getElementById('content').value;
    aceEditor.setValue(initialContent, -1); // -1 moves cursor to start
    
    // If editing and has content, extract title
    if (initialContent) {
        const title = extractTitleFromContent(initialContent);
        document.getElementById('title').value = title;
    }
    
    // Listen for changes in Ace Editor
    aceEditor.on('change', function() {
        syncContentAndUpdatePreview();
    });
    
    // Handle form submission - ensure content is synced
    document.getElementById('note-form').addEventListener('submit', function(e) {
        syncContentAndUpdatePreview();
        const submitBtn = this.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.textContent = 'Saving...';
    });
    
    // Set focus to ace editor
    aceEditor.focus();
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Ace Editor
    initializeAceEditor();
    
    // Initial preview
    updatePreview();
    
    // Add keyboard shortcuts
    if (aceEditor) {
        aceEditor.commands.addCommand({
            name: 'bold',
            bindKey: {win: 'Ctrl-B', mac: 'Command-B'},
            exec: function() { insertMarkdown('**', '**'); }
        });
        
        aceEditor.commands.addCommand({
            name: 'italic',
            bindKey: {win: 'Ctrl-I', mac: 'Command-I'},
            exec: function() { insertMarkdown('*', '*'); }
        });
        
        aceEditor.commands.addCommand({
            name: 'link',
            bindKey: {win: 'Ctrl-K', mac: 'Command-K'},
            exec: function() { insertMarkdown('[', '](url)'); }
        });
    }
    
    // Settings dropdown toggle
    const settingsBtn = document.getElementById('settings-toggle');
    const settingsDropdown = document.getElementById('settings-dropdown');
    
    function positionDropdown() {
        const btnRect = settingsBtn.getBoundingClientRect();
        const dropdownWidth = 320;
        const dropdownHeight = settingsDropdown.offsetHeight;
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        
        // Calculate position
        let left = btnRect.right - dropdownWidth;
        let top = btnRect.bottom + 8;
        
        // Adjust if it goes off the right edge
        if (left + dropdownWidth > viewportWidth - 20) {
            left = viewportWidth - dropdownWidth - 20;
        }
        
        // Adjust if it goes off the left edge
        if (left < 20) {
            left = 20;
        }
        
        // Adjust if it goes off the bottom
        if (top + dropdownHeight > viewportHeight - 20) {
            // Show above the button instead
            top = btnRect.top - dropdownHeight - 8;
        }
        
        settingsDropdown.style.left = left + 'px';
        settingsDropdown.style.top = top + 'px';
    }
    
    settingsBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        const isShowing = settingsDropdown.classList.contains('show');
        
        if (!isShowing) {
            settingsDropdown.classList.add('show');
            // Position after showing to get correct dimensions
            positionDropdown();
        } else {
            settingsDropdown.classList.remove('show');
        }
    });
    
    // Reposition on window resize
    window.addEventListener('resize', function() {
        if (settingsDropdown.classList.contains('show')) {
            positionDropdown();
        }
    });
    
    // Close settings dropdown when clicking outside
    document.addEventListener('click', function(e) {
        if (!settingsDropdown.contains(e.target) && !settingsBtn.contains(e.target)) {
            settingsDropdown.classList.remove('show');
        }
    });
    
    // Prevent dropdown from closing when clicking inside
    settingsDropdown.addEventListener('click', function(e) {
        e.stopPropagation();
    });
    
    // Preview panel collapse/expand
    const previewToggle = document.getElementById('preview-toggle');
    const previewPanel = document.getElementById('preview-panel');
    const editorLayout = document.querySelector('.editor-layout');
    
    previewToggle.addEventListener('click', function(e) {
        e.stopPropagation(); // Prevent event bubbling
        previewPanel.classList.toggle('collapsed');
        editorLayout.classList.toggle('preview-collapsed');
        
        // Resize Ace Editor after animation
        setTimeout(function() {
            if (aceEditor) {
                aceEditor.resize();
            }
        }, 300);
    });
    
    // Click on collapsed preview to expand
    previewPanel.addEventListener('click', function(e) {
        if (this.classList.contains('collapsed')) {
            this.classList.remove('collapsed');
            editorLayout.classList.remove('preview-collapsed');
            
            // Resize Ace Editor after animation
            setTimeout(function() {
                if (aceEditor) {
                    aceEditor.resize();
                }
            }, 300);
        }
    });
});
</script>

{% endblock %}