{% extends "layout.html" %}

{% block content %}
<div class="timetrack-container note-view-container">
    <div class="note-header">
        <div class="note-title-section">
            <h1>{{ note.title }}</h1>
            <div class="note-meta">
                <span class="visibility-badge visibility-{{ note.visibility.value.lower() }}">
                    {% if note.visibility.value == 'Private' %}🔒{% elif note.visibility.value == 'Team' %}👥{% else %}🏢{% endif %}
                    {{ note.visibility.value }}
                </span>
                <span class="author">By {{ note.created_by.username }}</span>
                <span class="date">Created {{ note.created_at|format_date }}</span>
                {% if note.updated_at > note.created_at %}
                <span class="date">· Updated {{ note.updated_at|format_date }}</span>
                {% endif %}
            </div>
        </div>
        
        <div class="note-actions">
            {% if note.can_user_edit(g.user) %}
            <a href="{{ url_for('edit_note', slug=note.slug) }}" class="btn btn-primary">Edit</a>
            <form method="POST" action="{{ url_for('delete_note', slug=note.slug) }}" style="display: inline;"
                  onsubmit="return confirm('Are you sure you want to delete this note?')">
                <button type="submit" class="btn btn-danger">Delete</button>
            </form>
            {% endif %}
            <a href="{{ url_for('notes_list') }}" class="btn btn-secondary">Back to Notes</a>
        </div>
    </div>

    <div class="note-associations">
        {% if note.project %}
        <div class="association-item">
            <span class="association-label">Project:</span>
            <span class="association-value">
                <a href="{{ url_for('manage_project_tasks', project_id=note.project.id) }}">
                    {{ note.project.code }} - {{ note.project.name }}
                </a>
            </span>
        </div>
        {% endif %}
        
        {% if note.task %}
        <div class="association-item">
            <span class="association-label">Task:</span>
            <span class="association-value">
                <a href="{{ url_for('view_task', task_id=note.task.id) }}">
                    #{{ note.task.id }} - {{ note.task.title }}
                </a>
            </span>
        </div>
        {% endif %}
        
        {% if note.tags %}
        <div class="association-item">
            <span class="association-label">Tags:</span>
            <span class="association-value">
                {% for tag in note.tags %}
                <a href="{{ url_for('notes_list', tag=tag) }}" class="tag-badge">{{ tag }}</a>
                {% endfor %}
            </span>
        </div>
        {% endif %}
    </div>

    <div class="note-content markdown-content">
        {{ note.render_html()|safe }}
    </div>

    {% if note.linked_notes or note.can_user_edit(g.user) %}
    <div class="linked-notes-section">
        <div class="section-header">
            <h3>Linked Notes</h3>
            {% if note.can_user_edit(g.user) %}
            <button id="add-link-btn" class="btn btn-sm btn-success">Add Link</button>
            {% endif %}
        </div>
        
        {% if outgoing_links or incoming_links %}
        <div class="linked-notes-grid">
            {% for link in outgoing_links %}
            <div class="linked-note-card">
                <div class="linked-note-header">
                    <h4><a href="{{ url_for('view_note', slug=link.target_note.slug) }}">{{ link.target_note.title }}</a></h4>
                    <span class="link-type">→ {{ link.link_type }}</span>
                </div>
                <div class="linked-note-preview">
                    {{ link.target_note.get_preview()|safe }}
                </div>
                {% if note.can_user_edit(g.user) %}
                <button class="remove-link-btn" data-target-id="{{ link.target_note_id }}">Remove Link</button>
                {% endif %}
            </div>
            {% endfor %}
            {% for link in incoming_links %}
            <div class="linked-note-card">
                <div class="linked-note-header">
                    <h4><a href="{{ url_for('view_note', slug=link.source_note.slug) }}">{{ link.source_note.title }}</a></h4>
                    <span class="link-type">← {{ link.link_type }}</span>
                </div>
                <div class="linked-note-preview">
                    {{ link.source_note.get_preview()|safe }}
                </div>
                {% if note.can_user_edit(g.user) %}
                <button class="remove-link-btn" data-target-id="{{ link.source_note_id }}">Remove Link</button>
                {% endif %}
            </div>
            {% endfor %}
        </div>
        {% else %}
        <p class="no-links">No linked notes yet.</p>
        {% endif %}
    </div>
    {% endif %}
</div>

<!-- Add Link Modal -->
{% if note.can_user_edit(g.user) %}
<div id="link-modal" class="modal" style="display: none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h3>Link to Another Note</h3>
        <form id="link-form">
            <div class="form-group">
                <label for="target-note">Select Note:</label>
                <select id="target-note" name="target_note_id" required>
                    <option value="">Choose a note...</option>
                    {% for other_note in linkable_notes %}
                    {% if other_note.id != note.id %}
                    <option value="{{ other_note.id }}">
                        {{ other_note.title }}
                        ({{ other_note.visibility.value }})
                    </option>
                    {% endif %}
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="link-type">Link Type:</label>
                <select id="link-type" name="link_type">
                    <option value="related">Related</option>
                    <option value="references">References</option>
                    <option value="parent">Parent</option>
                    <option value="child">Child</option>
                </select>
            </div>
            <div class="modal-actions">
                <button type="submit" class="btn btn-primary">Add Link</button>
                <button type="button" class="btn btn-secondary" id="cancel-link">Cancel</button>
            </div>
        </form>
    </div>
</div>
{% endif %}

<style>
/* Note view specific styles */
.note-view-container {
    max-width: 900px !important;
    margin: 0 auto !important;
    padding: 2rem !important;
}

.note-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 2rem;
    padding-bottom: 1.5rem;
    border-bottom: 2px solid #e9ecef;
}

.note-title-section h1 {
    margin: 0 0 0.5rem 0;
    font-size: 2.5rem;
    line-height: 1.2;
}

.note-meta {
    display: flex;
    gap: 1rem;
    align-items: center;
    flex-wrap: wrap;
    font-size: 0.9rem;
    color: #666;
}

.visibility-badge {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
}

.visibility-private {
    background: #f8d7da;
    color: #721c24;
}

.visibility-team {
    background: #d1ecf1;
    color: #0c5460;
}

.visibility-company {
    background: #d4edda;
    color: #155724;
}

.note-actions {
    display: flex;
    gap: 0.5rem;
}

.note-actions form {
    margin: 0;
}

.note-associations {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 2rem;
}

.association-item {
    display: flex;
    align-items: center;
    margin-bottom: 0.5rem;
}

.association-item:last-child {
    margin-bottom: 0;
}

.association-label {
    font-weight: 500;
    margin-right: 1rem;
    min-width: 80px;
}

.association-value {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.tag-badge {
    background: #e9ecef;
    color: #495057;
    padding: 0.2rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    text-decoration: none;
    transition: background 0.2s ease;
}

.tag-badge:hover {
    background: #dee2e6;
    color: #333;
}

.note-content {
    background: white;
    padding: 2rem;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    min-height: 300px;
}

.markdown-content {
    line-height: 1.6;
}

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

.markdown-content h1:first-child {
    margin-top: 0;
}

.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;
}

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

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

.section-header h3 {
    margin: 0;
}

.linked-notes-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1rem;
}

.linked-note-card {
    background: white;
    padding: 1rem;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    position: relative;
}

.linked-note-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 0.5rem;
}

.linked-note-header h4 {
    margin: 0;
    font-size: 1.1rem;
}

.linked-note-header a {
    color: #333;
    text-decoration: none;
}

.linked-note-header a:hover {
    color: var(--primary-color);
}

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

.linked-note-preview {
    color: #666;
    font-size: 0.9rem;
    line-height: 1.4;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.remove-link-btn {
    position: absolute;
    top: 0.5rem;
    right: 0.5rem;
    background: #dc3545;
    color: white;
    border: none;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.75rem;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.linked-note-card:hover .remove-link-btn {
    opacity: 1;
}

.no-links {
    color: #999;
    font-style: italic;
}

/* Modal styles */
.modal-content {
    max-width: 500px;
}

.modal-actions {
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
    margin-top: 1.5rem;
}

/* Responsive design */
@media (max-width: 768px) {
    .note-header {
        flex-direction: column;
        gap: 1rem;
    }
    
    .note-title-section h1 {
        font-size: 2rem;
    }
    
    .note-meta {
        font-size: 0.85rem;
    }
    
    .linked-notes-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
{% if note.can_user_edit(g.user) %}
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('link-modal');
    const addLinkBtn = document.getElementById('add-link-btn');
    const closeBtn = modal.querySelector('.close');
    const cancelBtn = document.getElementById('cancel-link');
    const linkForm = document.getElementById('link-form');
    
    // Open modal
    addLinkBtn.addEventListener('click', function() {
        modal.style.display = 'block';
    });
    
    // Close modal
    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    
    cancelBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });
    
    // Submit link form
    linkForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const targetNoteId = document.getElementById('target-note').value;
        const linkType = document.getElementById('link-type').value;
        
        fetch(`/api/notes/{{ note.id }}/link`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                target_note_id: parseInt(targetNoteId),
                link_type: linkType
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.message || 'Server error');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: ' + error.message);
        });
    });
    
    // Remove link buttons
    document.querySelectorAll('.remove-link-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const targetId = this.getAttribute('data-target-id');
            
            if (confirm('Are you sure you want to remove this link?')) {
                fetch(`/api/notes/{{ note.id }}/link`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        target_note_id: parseInt(targetId)
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while removing the link');
                });
            }
        });
    });
});
{% endif %}
</script>

{% endblock %}