{% extends 'base.html' %}
{% load help_tags %}

{% block title %}{{ title }}{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde@2.18.0/dist/easymde.min.css">
<style>
    .EasyMDEContainer {
        margin-bottom: 1rem;
    }
    
    .EasyMDEContainer .editor-toolbar {
        border-color: #dee2e6;
        background: #f8f9fa;
    }
    
    .EasyMDEContainer .CodeMirror {
        border-color: #dee2e6;
        font-family: inherit;
        font-size: 1rem;
        min-height: 300px;
    }
    
    .EasyMDEContainer .editor-preview,
    .EasyMDEContainer .editor-preview-side {
        font-family: inherit;
        font-size: 1rem;
        line-height: 1.5;
    }
    
    .editor-help {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 1rem;
        margin-top: 0.5rem;
    }
</style>
{% endblock %}

{% block content %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{% url 'stiftung:home' %}">Home</a></li>
        <li class="breadcrumb-item"><a href="{% url 'stiftung:geschichte_list' %}">Geschichte</a></li>
        {% if seite %}
        <li class="breadcrumb-item"><a href="{{ seite.get_absolute_url }}">{{ seite.titel }}</a></li>
        <li class="breadcrumb-item active" aria-current="page">Bearbeiten</li>
        {% else %}
        <li class="breadcrumb-item active" aria-current="page">Neue Seite</li>
        {% endif %}
    </ol>
</nav>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">
                    <i class="fas fa-{% if seite %}edit{% else %}plus{% endif %} me-2"></i>{{ title }}
                </h5>
            </div>
            <div class="card-body">
                <form method="post" id="geschichteForm">
                    {% csrf_token %}
                    
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <label class="form-label" for="{{ form.titel.id_for_label }}">{{ form.titel.label }}</label>
                            {{ form.titel }}
                            {% if form.titel.errors %}
                                <div class="text-danger">{{ form.titel.errors }}</div>
                            {% endif %}
                        </div>
                        <div class="col-md-4">
                            <label class="form-label" for="{{ form.sortierung.id_for_label }}">{{ form.sortierung.label }}</label>
                            {{ form.sortierung }}
                            {% if form.sortierung.errors %}
                                <div class="text-danger">{{ form.sortierung.errors }}</div>
                            {% endif %}
                            <div class="form-text">{{ form.sortierung.help_text }}</div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label" for="{{ form.slug.id_for_label }}">{{ form.slug.label }}</label>
                        {{ form.slug }}
                        {% if form.slug.errors %}
                            <div class="text-danger">{{ form.slug.errors }}</div>
                        {% endif %}
                        <div class="form-text">{{ form.slug.help_text }}</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label" for="{{ form.inhalt.id_for_label }}">{{ form.inhalt.label }}</label>
                        
                        <!-- Markdown Editor -->
                        {{ form.inhalt }}
                        
                        {% if form.inhalt.errors %}
                            <div class="text-danger">{{ form.inhalt.errors }}</div>
                        {% endif %}
                        <div class="form-text">{{ form.inhalt.help_text }}</div>
                        
                        <div class="editor-help mt-2">
                            <h6><i class="fas fa-info-circle me-1"></i>Markdown-Hilfe</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <small>
                                        <strong>Formatierung:</strong><br>
                                        <code>**Fett**</code> → <strong>Fett</strong><br>
                                        <code>*Kursiv*</code> → <em>Kursiv</em><br>
                                        <code>~~Durchgestrichen~~</code> → <del>Durchgestrichen</del>
                                    </small>
                                </div>
                                <div class="col-md-6">
                                    <small>
                                        <strong>Überschriften:</strong><br>
                                        <code># Überschrift 1</code><br>
                                        <code>## Überschrift 2</code><br>
                                        <code>### Überschrift 3</code>
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3 form-check">
                        {{ form.ist_veroeffentlicht }}
                        <label class="form-check-label" for="{{ form.ist_veroeffentlicht.id_for_label }}">
                            {{ form.ist_veroeffentlicht.label }}
                        </label>
                        {% if form.ist_veroeffentlicht.errors %}
                            <div class="text-danger">{{ form.ist_veroeffentlicht.errors }}</div>
                        {% endif %}
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="{% if seite %}{{ seite.get_absolute_url }}{% else %}{% url 'stiftung:geschichte_list' %}{% endif %}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left me-1"></i>Abbrechen
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-1"></i>Speichern
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header bg-info text-white">
                <h6 class="mb-0"><i class="fas fa-markdown me-2"></i>Markdown Editor</h6>
            </div>
            <div class="card-body">
                <p class="small">Der Markdown-Editor unterstützt:</p>
                <ul class="small">
                    <li>Live-Vorschau beim Schreiben</li>
                    <li>Toolbar für häufige Formatierungen</li>
                    <li>Vollbild-Modus für fokussiertes Schreiben</li>
                    <li>Automatisches Speichern im Browser</li>
                </ul>
                <hr>
                <h6 class="small">Häufige Markdown-Syntax:</h6>
                <div class="small">
                    <code>- Listen-Element</code><br>
                    <code>1. Nummerierte Liste</code><br>
                    <code>[Link Text](URL)</code><br>
                    <code>&gt; Zitat</code><br>
                    <code>`Code`</code>
                </div>
                <hr>
                <p class="small text-muted">
                    Tipp: Verwenden Sie die Bild-Upload-Funktion, um Bilder zur Seite hinzuzufügen.
                </p>
            </div>
        </div>

        {% if geschichte_dokumente %}
        <div class="card mt-3">
            <div class="card-header bg-dark text-white">
                <h6 class="mb-0"><i class="fas fa-landmark me-2"></i>Dokumente verknüpfen</h6>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    {% for dok in geschichte_dokumente %}
                    <label class="list-group-item list-group-item-action" style="cursor: pointer;">
                        <div class="d-flex align-items-start">
                            <input type="checkbox" name="dokument_ids" value="{{ dok.pk }}"
                                   class="form-check-input me-2 mt-1"
                                   form="geschichteForm"
                                   {% if dok.pk in selected_dok_ids %}checked{% endif %}>
                            <div class="flex-grow-1">
                                <div class="small fw-bold">{{ dok.titel|truncatechars:40 }}</div>
                                <small class="text-muted">{{ dok.dateiname_original }} ({{ dok.get_human_size }})</small>
                                <br><small class="text-muted">{{ dok.erstellt_am|date:"d.m.Y" }}</small>
                            </div>
                            <a href="{% url 'stiftung:dms_download' dok.pk %}" class="btn btn-sm btn-outline-primary ms-1" title="Herunterladen" onclick="event.stopPropagation();">
                                <i class="fas fa-download"></i>
                            </a>
                        </div>
                    </label>
                    {% endfor %}
                </div>
            </div>
            <div class="card-footer small text-muted">
                Dokumente aus dem DMS mit Kontext "Stiftungsgeschichte" auswählen, um sie mit diesem Beitrag zu verknüpfen.
            </div>
        </div>
        {% else %}
        <div class="card mt-3">
            <div class="card-header bg-dark text-white">
                <h6 class="mb-0"><i class="fas fa-landmark me-2"></i>Dokumente verknüpfen</h6>
            </div>
            <div class="card-body text-muted small">
                Keine Stiftungsgeschichte-Dokumente im DMS vorhanden. Laden Sie Dokumente mit dem Kontext "Stiftungsgeschichte" im <a href="{% url 'stiftung:dms_upload' %}?kontext=stiftungsgeschichte">DMS hoch</a>.
            </div>
        </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/easymde@2.18.0/dist/easymde.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('Initializing EasyMDE markdown editor...');
    
    var textarea = document.getElementById('id_inhalt');
    
    if (textarea) {
        var easyMDE = new EasyMDE({
            element: textarea,
            autofocus: false,
            autosave: {
                enabled: true,
                delay: 1000,
                uniqueId: 'geschichte_' + (window.location.pathname.match(/\/(\w+)\//) || ['', 'new'])[1]
            },
            spellChecker: false,
            toolbar: [
                'bold', 'italic', 'strikethrough', '|',
                'heading-1', 'heading-2', 'heading-3', '|',
                'unordered-list', 'ordered-list', '|',
                'link', 'quote', 'code', '|',
                'preview', 'side-by-side', 'fullscreen', '|',
                'guide'
            ],
            placeholder: 'Schreiben Sie hier den Inhalt der Geschichtsseite...\n\nSie können Markdown verwenden für:\n- **Fettdruck**\n- *Kursiv*\n- # Überschriften\n- [Links](URL)\n- Listen und vieles mehr',
            renderingConfig: {
                singleLineBreaks: false,
                codeSyntaxHighlighting: false
            },
            previewRender: function(plainText) {
                // Simple markdown to HTML conversion for preview
                return plainText
                    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
                    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
                    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
                    .replace(/^\> (.*$)/gim, '<blockquote>$1</blockquote>')
                    .replace(/\*\*(.*)\*\*/gim, '<strong>$1</strong>')
                    .replace(/\*(.*)\*/gim, '<em>$1</em>')
                    .replace(/~~(.*)~~/gim, '<del>$1</del>')
                    .replace(/`([^`]*)`/gim, '<code>$1</code>')
                    .replace(/\[([^\]]*)\]\(([^)]*)\)/gim, '<a href="$2">$1</a>')
                    .replace(/^\* (.*$)/gim, '<li>$1</li>')
                    .replace(/^\d+\. (.*$)/gim, '<li>$1</li>')
                    .replace(/\n/gim, '<br>');
            },
            status: ['autosave', 'lines', 'words', 'cursor'],
            insertTexts: {
                horizontalRule: ["", "\n\n-----\n\n"],
                image: ["![", "](http://)"],
                link: ["[", "](http://)"],
                table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text     | Text     |\n\n"],
            }
        });
        
        console.log('EasyMDE initialized successfully');
        
        // Auto-generate slug from title
        var titleField = document.querySelector('input[name="titel"]');
        var slugField = document.querySelector('input[name="slug"]');
        
        if (titleField && slugField) {
            titleField.addEventListener('input', function() {
                // Only auto-generate if slug is empty or matches previous title
                if (!slugField.value || slugField.getAttribute('data-auto-generated') === 'true') {
                    var title = this.value;
                    var slug = title.toLowerCase()
                        .replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
                        .replace(/[^\w\s-]/g, '')
                        .replace(/[-\s]+/g, '-')
                        .replace(/^-+|-+$/g, '');
                    slugField.value = slug;
                    slugField.setAttribute('data-auto-generated', 'true');
                }
            });
            
            // Mark slug as manually edited if user changes it
            slugField.addEventListener('input', function() {
                slugField.setAttribute('data-auto-generated', 'false');
            });
        }
    }
});
</script>
{% endblock %}