{% extends 'base.html' %}
{% load i18n %}
{% load static %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'simplemde/simplemde.min.css' %}">
{# Select2 CSS now loaded globally from vendor in base.html #}
<style>
    .CodeMirror {
        height: 400px;
        border-radius: 0.375rem;
    }
    .editor-toolbar {
        border-top-left-radius: 0.375rem;
        border-top-right-radius: 0.375rem;
    }
    .CodeMirror {
        border-bottom-left-radius: 0.375rem;
        border-bottom-right-radius: 0.375rem;
    }
    .select2-container--default .select2-selection--multiple {
        border-color: #D1D5DB;
        border-radius: 0.375rem;
    }
    .select2-container--default.select2-container--focus .select2-selection--multiple {
        border-color: #3B82F6;
        box-shadow: 0 0 0 1px #3B82F6;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: #EFF6FF;
        border: 1px solid #BFDBFE;
        color: #1D4ED8;
        border-radius: 0.375rem;
        padding: 2px 8px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        color: #1D4ED8;
        margin-right: 5px;
    }
</style>
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="bg-white shadow-sm rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:p-6">
            <h1 class="text-2xl font-bold text-gray-900 mb-6">
                {% if form.instance.pk %}
                    {% trans "Edit Post" %}
                {% else %}
                    {% trans "New Post" %}
                {% endif %}
            </h1>

            <form method="post" class="space-y-6">
                {% csrf_token %}

                <!-- Title Field -->
                <div>
                    <label for="{{ form.title.id_for_label }}" class="block text-sm font-medium text-gray-700">
                        {{ form.title.label }}
                    </label>
                    <div class="mt-1">
                        <input type="text" name="{{ form.title.name }}" id="{{ form.title.id_for_label }}"
                               class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"
                               value="{{ form.title.value|default:'' }}"
                               placeholder="{% trans 'Post Title' %}">
                    </div>
                    {% if form.title.errors %}
                    <p class="mt-2 text-sm text-red-600">{{ form.title.errors.0 }}</p>
                    {% endif %}
                </div>

                <!-- Tags Field -->
                <div>
                    <label for="{{ form.tags.id_for_label }}" class="block text-sm font-medium text-gray-700">
                        {{ form.tags.label }}
                    </label>
                    <div class="mt-1">
                        <select name="{{ form.tags.name }}" id="{{ form.tags.id_for_label }}"
                                class="select2 shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"
                                multiple="multiple">
                            {% for tag in form.tags.field.queryset %}
                                <option value="{{ tag.pk }}" {% if form.instance.pk and tag.pk in form.tags.value %}selected{% endif %}>
                                    {{ tag.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    {% if form.tags.errors %}
                    <p class="mt-2 text-sm text-red-600">{{ form.tags.errors.0 }}</p>
                    {% endif %}
                    <p class="mt-2 text-sm text-gray-500">{% trans "Select existing tags or create new ones" %}</p>
                </div>

                <!-- Content Field with SimpleMDE -->
                <div>
                    <label for="{{ form.content.id_for_label }}" class="block text-sm font-medium text-gray-700">
                        {{ form.content.label }}
                    </label>
                    <div class="mt-1">
                        <textarea name="{{ form.content.name }}" id="{{ form.content.id_for_label }}"
                                  class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">{{ form.content.value|default:'' }}</textarea>
                    </div>
                    {% if form.content.errors %}
                    <p class="mt-2 text-sm text-red-600">{{ form.content.errors.0 }}</p>
                    {% endif %}
                    <p class="mt-2 text-sm text-gray-500">{% trans "Supports Markdown formatting" %}</p>
                </div>

                <div class="pt-5">
                    <div class="flex justify-end space-x-3">
                        <a href="{% url 'post-list' %}"
                           class="inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            {% trans "Cancel" %}
                        </a>
                        <button type="submit"
                                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            {% trans "Save" %}
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'simplemde/simplemde.min.js' %}"></script>
{# jQuery and Select2 are now loaded globally from vendor in base.html #}
<script>
// Clear SimpleMDE autosave cache to prevent old cached content from overriding DB updates
// This is especially important after task list checkbox toggles
var postId = '{{ form.instance.pk|default:"new" }}';
var cacheKey = 'smde_post_content_' + postId;
if (postId !== 'new') {
    // Check if the cached timestamp is older than the updated_at timestamp
    var cachedData = localStorage.getItem(cacheKey);
    if (cachedData) {
        try {
            var parsedCache = JSON.parse(cachedData);
            var updatedAt = new Date('{{ form.instance.updated_at.isoformat }}').getTime();
            var cacheTime = parsedCache.ts || 0;
            // If cache is older than last update, clear it
            if (cacheTime < updatedAt) {
                localStorage.removeItem(cacheKey);
            }
        } catch (e) {
            // If parsing fails, clear the cache
            localStorage.removeItem(cacheKey);
        }
    }
}

// Initialize SimpleMDE with custom task list button
var simplemde = new SimpleMDE({
    element: document.getElementById("{{ form.content.id_for_label }}"),
    spellChecker: false,
    autosave: {
        enabled: true,
        unique_id: "post_content_{{ form.instance.pk|default:'new' }}"
    },
    toolbar: [
        "bold", "italic", "heading", "|",
        "quote", "unordered-list", "ordered-list", "|",
        {
            name: "task-list",
            action: function customTaskList(editor) {
                var cm = editor.codemirror;
                var selection = cm.getSelection();
                var lines = selection.split('\n');

                if (lines.length > 0 && lines[0].match(/^- \[[ xX]\] /)) {
                    // Remove task list formatting
                    var newText = lines.map(function(line) {
                        return line.replace(/^- \[[ xX]\] /, '- ');
                    }).join('\n');
                    cm.replaceSelection(newText);
                } else if (selection) {
                    // Add task list formatting to selection
                    var newText = lines.map(function(line) {
                        if (line.trim()) {
                            return '- [ ] ' + line.replace(/^[-*]\s*/, '');
                        }
                        return line;
                    }).join('\n');
                    cm.replaceSelection(newText);
                } else {
                    // Insert a single task list item
                    cm.replaceSelection('- [ ] ');
                }
                cm.focus();
            },
            className: "fa fa-check-square",
            title: "Task List (- [ ] item)",
        },
        "|",
        "link", "image", "table", "|",
        "preview", "side-by-side", "fullscreen", "|",
        "guide"
    ],
    status: ["autosave", "lines", "words", "cursor"],
    renderingConfig: {
        singleLineBreaks: false,
        codeSyntaxHighlighting: true,
    }
});

// Initialize Select2 for tags with tag creation support
$(document).ready(function() {
    $('.select2').select2({
        tags: true,
        tokenSeparators: [','],
        placeholder: "{% trans 'Select or create tags' %}",
        allowClear: true,
        theme: "classic"
    });
});
</script>
{% endblock %}
