{% load i18n %}
{% if form.instance.id %}
<form id="editForm" hx-post="{% url "view-mail-template" form.instance.id %}" hx-target="#viewTemplateModalBody">
{% else %}
<form id="createForm" hx-post="{% url "create-mail-template" %}" hx-target="#viewTemplateModalBody">
{% endif %}
    <section>
        <div id="viewTemplateModalContainer">
            <div class="my-3" id="keyResultCard">
                <div class="oh-card oh-card--no-shadow oh-card__body">
                    <div class="oh-input__group">
                        <label class="oh-input__label mt-0" for="keyTitle">{% trans "Title" %}</label>
                        {{ form.title }}
                    </div>
                    <div class="oh-input__group">
                        <label class="oh-input__label mt-2" for="keyTitle">{% trans "Body" %}</label>
                        {{ form.body }}
                    </div>
                    <div class="form-hint" style="margin-top: 10px; font-size: 14px; color: #888;">
                        {% trans "Hint: Type '{' to get sender or receiver data" %}
                    </div>
                    <div class="oh-input__group">
                        <label class="oh-input__label mt-2" for="keyTitle">{% trans "Company" %}</label>
                        {{ form.company_id }}
                    </div>
                </div>
            </div>
        </div>
    </section>
    <button id="submitFormButton" type="submit" hidden ></button>
</form>
<script>
    $(document).ready(function () {
        function initializeSummernote() {
            {% if form.instance.title %}
                setModalLabel("{{ form.instance.title|escapejs }}", "#viewTemplateModalLabel");
            {% endif %}
            var searchWords = {{ searchWords|safe }};
            var mentions = Object.keys(searchWords);
            $("#id_body").summernote({
                hint: {
                    mentions: mentions,
                    match: /\B{(\w*)$/,
                    search: function (keyword, callback) {
                        var pattern = new RegExp(keyword, "i"); // Case-insensitive search
                        callback($.grep(this.mentions, function (item) {
                            return pattern.test(item);
                        }));
                    },
                    content: function (item) {
                        var word = searchWords[item];
                        return "{% templatetag openbrace %}{% templatetag openbrace %}"+ word +"{% templatetag closebrace %}{% templatetag closebrace %}";
                    }
                }
            });
        }
        // Initial Summernote initialization
        initializeSummernote();

        // Re-initialize Summernote after HTMX content swap
        document.body.addEventListener('htmx:afterSwap', function (event) {
            initializeSummernote();
        });
    });
</script>
