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

{% block extra_css %}
    <link rel="stylesheet" href="{% static 'simplemde/simplemde.min.css' %}">
    <style>
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 4px;
        }
        .select2-container--classic .select2-selection--multiple {
            border: 1px solid #d1d5db !important;
            border-radius: 0.375rem !important;
            min-height: 38px !important;
        }
        .select2-container--classic .select2-selection--multiple .select2-selection__choice {
            background-color: #e5e7eb !important;
            border: 1px solid #d1d5db !important;
            border-radius: 0.25rem !important;
            padding: 2px 8px !important;
            margin: 3px !important;
        }
        /* ── Apple-style Action card picker ── */
        .action-type-radio { display: none; }
        .action-card {
            display: flex; align-items: center; gap: 1rem;
            border: 2px solid #e5e7eb; border-radius: 14px;
            padding: 0.9rem 1.1rem; cursor: pointer;
            transition: border-color .2s, background .2s, box-shadow .2s;
            background: #fff;
        }
        .action-card:hover { border-color: #c4b5fd; background: #faf9ff; }
        .action-card.selected { border-color: #8b5cf6; background: #f5f3ff; box-shadow: 0 0 0 3px rgba(139,92,246,.12); }
        .action-card-icon {
            width: 2.6rem; height: 2.6rem; flex-shrink: 0;
            border-radius: 12px; background: #f5f3ff; color: #7c3aed;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.3rem;
        }
        .action-card-title { font-weight: 600; font-size: .95rem; color: #1f2937; }
        .action-card-desc { font-size: .8rem; color: #6b7280; margin-top: 2px; line-height: 1.4; }
        .action-card-check {
            margin-left: auto; width: 1.5rem; height: 1.5rem; flex-shrink: 0;
            border-radius: 50%; border: 2px solid #d1d5db;
            display: flex; align-items: center; justify-content: center;
            color: transparent; font-size: .8rem; transition: all .2s;
        }
        .action-card.selected .action-card-check { background: #8b5cf6; border-color: #8b5cf6; color: #fff; }
        /* ── Message preview bubble (Discord-like) ── */
        .msg-preview {
            margin-top: .6rem; border-radius: 14px; background: #f9fafb;
            border: 1px solid #e5e7eb; padding: .7rem .9rem;
        }
        .msg-preview-label { font-size: .7rem; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: .04em; margin-bottom: .45rem; }
        .msg-preview-chat {
            background: #313338; border-radius: 12px; padding: .6rem .8rem;
            display: flex; gap: .6rem; align-items: flex-start;
        }
        .msg-preview-avatar {
            width: 2rem; height: 2rem; flex-shrink: 0; border-radius: 50%;
            background: linear-gradient(135deg, #5865F2, #7c3aed);
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-size: .9rem; font-weight: 700;
        }
        .msg-preview-author { font-size: .82rem; font-weight: 600; color: #e2e3e7; margin-bottom: 2px; }
        .msg-preview-text { font-size: .85rem; color: #dcddde; line-height: 1.4; word-break: break-word; }
        .msg-preview-text .qchip {
            background: #ede9fe; color: #6d28d9; border-radius: 6px;
            padding: 0 .3rem; font-weight: 600;
        }
        .msg-preview-hint { font-size: .72rem; color: #9ca3af; margin-top: .45rem; }
        /* ── Sketch-style template parameter builder ── */
        .template-builder {
            margin-top: .8rem;
            border: 1px solid #e9e5f5; border-radius: 14px;
            background: linear-gradient(180deg, #faf9ff 0%, #f7f5fc 100%);
            padding: .9rem 1rem;
        }
        .tpl-label { font-size: .7rem; font-weight: 600; color: #7c6ba6; text-transform: uppercase; letter-spacing: .06em; }
        .tpl-toggle {
            display: inline-flex; align-items: center; gap: .35rem;
            margin-top: .6rem; border: 1px dashed #c4b5fd; background: #faf9ff;
            color: #6d28d9; border-radius: 10px;
            padding: .45rem 1rem; font-size: .85rem; font-weight: 600;
            cursor: pointer; transition: all .15s;
        }
        .tpl-toggle:hover { background: #ede9fe; border-color: #a78bfa; }
        .tpl-toggle.open { border-style: solid; background: #ede9fe; }
        .tpl-hint { font-size: .72rem; color: #9ca3af; margin-top: .2rem; line-height: 1.4; }
        .tpl-chip {
            display: inline-flex; align-items: center; gap: .35rem;
            border: 1px solid #ddd6fe; background: #fff;
            color: #6d28d9; border-radius: 980px;
            padding: .38rem 1rem; font-size: .88rem; font-weight: 600;
            cursor: pointer; transition: all .15s;
        }
        .tpl-chip:hover { background: #ede9fe; border-color: #a78bfa; box-shadow: 0 1px 4px rgba(109,40,217,.15); }
        .tpl-chip:active { transform: scale(.96); }
        .tpl-chip .tpl-chip-sub { font-weight: 400; color: #a78bfa; font-size: .78rem; }
        .tpl-chip .tpl-chip-name { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
        .tpl-chip.used { opacity: .45; pointer-events: none; }
        .tpl-param-list { margin-top: .7rem; display: flex; flex-direction: column; gap: .4rem; }
        .tpl-param-row { display: flex; align-items: center; gap: .55rem; }
        .tpl-param-name {
            font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
            background: #ede9fe; color: #6d28d9; border-radius: 7px;
            padding: .2rem .55rem; font-size: .82rem; font-weight: 600;
            min-width: 4.5rem; text-align: center; flex-shrink: 0;
        }
        .tpl-param-default {
            flex: 1; max-width: 320px;
            border: 1px solid #d1d5db; border-radius: 8px;
            padding: .35rem .6rem; font-size: .85rem; color: #374151;
            background: #fff; outline: none;
        }
        .tpl-param-default:focus { border-color: #8b5cf6; box-shadow: 0 0 0 3px rgba(139,92,246,.12); }
        .tpl-param-label { font-size: .72rem; color: #9ca3af; width: 3.2rem; flex-shrink: 0; }
        .tpl-param-del {
            background: none; border: none; cursor: pointer;
            color: #c4b5fd; font-size: .8rem; padding: .3rem .45rem; border-radius: 6px;
        }
        .tpl-param-del:hover { color: #ef4444; background: #fef2f2; }
        .tpl-add-row { display: flex; align-items: center; gap: .5rem; margin-top: .75rem; flex-wrap: wrap; }
        .tpl-add-row input {
            border: 1px solid #d1d5db; border-radius: 8px;
            padding: .38rem .65rem; font-size: .85rem; outline: none; background: #fff;
        }
        .tpl-add-row input:focus { border-color: #8b5cf6; box-shadow: 0 0 0 3px rgba(139,92,246,.12); }
        .tpl-add-name { width: 8rem; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
        .tpl-add-def { width: 10rem; }
        .tpl-add-btn {
            border: none; background: #7c3aed; color: #fff;
            border-radius: 8px; padding: .4rem .9rem; font-size: .82rem; font-weight: 600;
            cursor: pointer; transition: background .15s;
        }
        .tpl-add-btn:hover { background: #6d28d9; }
        .tpl-preview {
            margin-top: .75rem; border-radius: 10px;
            background: #23252b; padding: .6rem .85rem;
            font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
            font-size: .8rem; color: #d1d5db; word-break: break-all; line-height: 1.5;
        }
        .tpl-preview-label { font-size: .7rem; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: .06em; margin-bottom: .35rem; }
        .tpl-preview-url { white-space: pre-wrap; }
        .tpl-preview-val { color: #34d399; font-weight: 600; }
        .tpl-preview-req { color: #f87171; font-weight: 600; }
        .tpl-preview-note { font-size: .7rem; color: #9ca3af; margin-top: .3rem; }
        .tpl-empty { font-size: .78rem; color: #9ca3af; padding: .3rem 0; }
    </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-md rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
            <h1 class="text-2xl font-bold text-gray-900">
                {% if form.instance.pk %}{% trans "Edit Link" %}{% else %}{% trans "New Link" %}{% endif %}
            </h1>
        </div>
        <div class="px-4 py-5 sm:p-6">
            <!-- Link Type Tabs -->
            <div class="mb-4">
                <div class="flex border-b border-gray-200">
                    <button type="button" class="py-2 px-4 text-sm font-medium text-center {% if not is_custom and not is_action %}text-blue-600 border-b-2 border-blue-600{% else %}text-gray-500 border-b-2 border-transparent{% endif %} hover:text-blue-700 hover:border-blue-700 focus:outline-none" id="link-tab">
                        {% trans "Link" %}
                    </button>
                    <button type="button" class="py-2 px-4 text-sm font-medium text-center {% if is_custom %}text-green-600 border-b-2 border-green-600{% else %}text-gray-500 border-b-2 border-transparent{% endif %} hover:text-green-700 hover:border-green-300 focus:outline-none" id="custom-tab">
                        {% trans "Custom" %}
                    </button>
                    <button type="button" class="py-2 px-4 text-sm font-medium text-center {% if is_action %}text-purple-600 border-b-2 border-purple-600{% else %}text-gray-500 border-b-2 border-transparent{% endif %} hover:text-purple-700 hover:border-purple-300 focus:outline-none" id="action-tab">
                        ⚡ {% trans "Action" %}
                    </button>
                </div>
            </div>

            <!-- Link Type Description -->
            <div id="link-description" class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-4 {% if is_custom or is_action %}hidden{% endif %}">
                <p class="text-sm text-blue-700">
                    {% trans "Link type is used for redirecting to an external URL. Use this when you want to create a short alias for a long URL." %}
                </p>
                <p class="text-sm text-blue-700 mt-2">
                    {% trans "For dynamic URLs with parameters, click “Add template parameters” below the URL field." %}
                </p>
            </div>
            <div id="custom-description" class="bg-green-50 border-l-4 border-green-400 p-4 mb-4 {% if not is_custom %}hidden{% endif %}">
                <p class="text-sm text-green-700">
                    {% trans "Custom type allows you to create a link with custom HTML content. Use this when you want to display a message or custom content instead of redirecting." %}
                </p>
            </div>
            <div id="action-description" class="bg-purple-50 border-l-4 border-purple-400 p-4 mb-4 {% if not is_action %}hidden{% endif %}">
                <p class="text-sm text-purple-700">
                    ⚡ 动作链接：打开链接时自动执行一个动作。链接后面跟的字会变成消息内容发给小黑。
                </p>
            </div>

            <!-- Form -->
            <form method="post" class="space-y-6">
                {% csrf_token %}
                {% if form.non_field_errors %}
                    <div class="bg-red-50 border-l-4 border-red-400 p-4 mb-4">
                        {% for error in form.non_field_errors %}
                            <p class="text-sm text-red-700">{{ error }}</p>
                        {% endfor %}
                    </div>
                {% endif %}
                <input type="hidden" name="link_type" id="id_link_type" value="{{ form.link_type.value|default:'LINK' }}">
                {% for field in form %}
                    {% if field.name != 'link_type' and field.name != 'action_config' %}
                        <!-- Render fields based on link type -->
                        <div class="space-y-1 {% if field.name == 'original_url' %}link-field {% if is_custom or is_action %}hidden{% endif %}{% elif field.name == 'text' %} custom-field {% if not is_custom %}hidden{% endif %}{% elif field.name == 'action_type' or field.name == 'action_message_template' %}action-field {% if not is_action %}hidden{% endif %}{% endif %}">
                            <label for="{{ field.id_for_label }}" class="block text-sm font-medium text-gray-700 {% if field.name == 'original_url' and is_custom or field.name == 'text' and not is_custom or field.name == 'action_type' and not is_action or field.name == 'action_message_template' and not is_action %}hidden{% endif %} {% if field.name != 'description' and field.name != 'action_type' and field.name != 'action_message_template' %}required-field{% endif %}">
                                {{ field.label }}
                            </label>
                            <div class="mt-1">
                                {% if field.name == 'text' %}
                                    <!-- Render text field only for custom links -->
                                    {% if is_custom or is_new %}
                                        {{ field }}
                                    {% endif %}
                                {% elif field.name == 'original_url' %}
                                    <!-- Render original_url field for Link & Template links -->
                                    {% if not is_custom and not is_action %}
                                        <input type="{{ field.field.widget.input_type }}"
                                               name="{{ field.name }}"
                                               id="{{ field.id_for_label }}"
                                               value="{{ field.value|default_if_none:'' }}"
                                               class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                               {% if field.field.required %}required{% endif %}>
                                        <!-- Sketch-style template builder (Link type; auto-shows when the URL has {params}) -->
                                        <button type="button" id="tpl-toggle" class="tpl-toggle">🔧 <span id="tpl-toggle-label">{% trans "Add template parameters" %}</span></button>
                                        <div id="template-builder" class="template-builder hidden">
                                            <div class="tpl-label">🔧 {% trans "Template parameters" %}</div>
                                            <div class="tpl-hint">{% trans "Click a parameter to insert it into the URL. The text after go/alias/… fills the parameter when the link is opened." %}</div>
                                            <div class="tpl-chips" id="tpl-chips">
                                                <button type="button" class="tpl-chip" data-param="q"><span class="tpl-chip-sub">{</span>q<span class="tpl-chip-sub">}</span><span class="tpl-chip-sub">搜索词</span></button>
                                                <button type="button" class="tpl-chip" data-param="id" data-def=""><span class="tpl-chip-sub">{</span>id<span class="tpl-chip-sub">}</span><span class="tpl-chip-sub">编号</span></button>
                                                <button type="button" class="tpl-chip" data-param="page" data-def="1"><span class="tpl-chip-sub">{</span>page<span class="tpl-chip-sub">}</span><span class="tpl-chip-sub">页码</span></button>
                                                <button type="button" class="tpl-chip" data-param="category"><span class="tpl-chip-sub">{</span>category<span class="tpl-chip-sub">}</span><span class="tpl-chip-sub">分类</span></button>
                                                <button type="button" class="tpl-chip" data-param="keyword"><span class="tpl-chip-sub">{</span>keyword<span class="tpl-chip-sub">}</span><span class="tpl-chip-sub">关键词</span></button>
                                                <button type="button" class="tpl-chip" data-param="lang"><span class="tpl-chip-sub">{</span>lang<span class="tpl-chip-sub">}</span><span class="tpl-chip-sub">语言</span></button>
                                            </div>
                                            <div class="tpl-param-list" id="tpl-param-list"></div>
                                            <div class="tpl-add-row">
                                                <input type="text" id="tpl-new-name" class="tpl-add-name" placeholder="{% trans 'param name' %}" aria-label="{% trans 'New parameter name' %}">
                                                <input type="text" id="tpl-new-default" class="tpl-add-def" placeholder="{% trans 'default value (optional)' %}" aria-label="{% trans 'New parameter default' %}">
                                                <button type="button" class="tpl-add-btn" id="tpl-add-param">+ {% trans "Add" %}</button>
                                            </div>
                                            <div class="tpl-preview">
                                                <div class="tpl-preview-label">{% trans "Live preview" %}</div>
                                                <div class="tpl-preview-url" id="tpl-preview-url"></div>
                                            </div>
                                        </div>
                                    {% endif %}
                                {% elif field.name == 'action_type' %}
                                    <!-- Apple-style action card picker -->
                                    {% if is_action or is_new %}
                                        <div class="action-card {% if field.value == 'discord_send' %}selected{% endif %}" id="action-card-discord_send">
                                            <input type="radio" name="{{ field.html_name }}"
                                                   id="id_action_type_discord_send"
                                                   value="discord_send"
                                                   class="action-type-radio"
                                                   {% if field.value == 'discord_send' %}checked{% endif %}>
                                            <div class="action-card-icon">💬</div>
                                            <div>
                                                <div class="action-card-title">发消息到 Discord</div>
                                                <div class="action-card-desc">打开链接时，把链接后面的文字发到 Discord 频道，小黑会收到并回复</div>
                                            </div>
                                            <div class="action-card-check">✓</div>
                                        </div>
                                    {% endif %}
                                {% elif field.name == 'action_message_template' %}
                                    <!-- Render action config fields only for action links -->
                                    {% if is_action or is_new %}
                                        {{ field }}
                                        <div class="msg-preview" id="msg-preview">
                                            <div class="msg-preview-label">发送效果预览</div>
                                            <div class="msg-preview-chat">
                                                <div class="msg-preview-avatar">黑</div>
                                                <div>
                                                    <div class="msg-preview-author">小黑</div>
                                                    <div class="msg-preview-text" id="msg-preview-text">{{ field.value|default:'@小黑 帮我看看 {query}' }}</div>
                                                </div>
                                            </div>
                                            <div class="msg-preview-hint">别人打开 go/ask/今天天气 时，消息里的 <span class="qchip">今天天气</span> 会被自动替换成链接后面的字</div>
                                        </div>
                                    {% endif %}
                                {% elif field.name == 'alias' and form.instance.pk %}
                                    <!-- Render alias field as read-only when editing -->
                                    <input type="text"
                                           name="{{ field.name }}"
                                           id="{{ field.id_for_label }}"
                                           value="{{ field.value|default_if_none:'' }}"
                                           class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                           readonly>
                                    <p class="mt-2 text-sm text-yellow-600">{% trans "Alias cannot be changed after creation." %}</p>
                                {% elif field.name == 'tags' %}
                                    <!-- Render tags field with Select2 -->
                                    {{ field }}
                                {% else %}
                                    <!-- Render other fields normally -->
                                    <input type="{{ field.field.widget.input_type }}"
                                           name="{{ field.name }}"
                                           id="{{ field.id_for_label }}"
                                           value="{{ field.value|default_if_none:'' }}"
                                           class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                           {% if field.field.required %}required{% endif %}>
                                {% endif %}
                            </div>
                            {% if field.errors %}
                                <ul class="mt-1 text-sm text-red-600">
                                    {% for error in field.errors %}
                                        <li>{{ error }}</li>
                                    {% endfor %}
                                </ul>
                            {% endif %}
                            {% if field.help_text %}
                                <p class="mt-2 text-sm text-gray-500">{{ field.help_text }}</p>
                            {% endif %}
                        </div>
                    {% endif %}
                {% endfor %}
                <div class="flex justify-end space-x-3 mt-6">
                    <a href="{% url 'link_list' %}" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-gray-700 bg-gray-200 hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-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>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
    <script src="{% static 'simplemde/simplemde.min.js' %}"></script>
    {# jQuery and Select2 are loaded globally from vendor in base.html #}
    <script>
        $(document).ready(function() {
            // Initialize Select2 for tags
            $('#id_tags').select2({
                theme: 'classic',
                width: '100%',
                placeholder: '{% trans "Select tags" %}',
                allowClear: true,
                tags: true, // Allow creating new tags
                tokenSeparators: [',', ' '],
                createTag: function(params) {
                    var term = $.trim(params.term).toLowerCase();
                    if (term === '') {
                        return null;
                    }
                    return {
                        id: term,
                        text: term,
                        newTag: true
                    };
                }
            });
        });
        document.addEventListener('DOMContentLoaded', function() {
            const linkTab = document.getElementById('link-tab');
            const customTab = document.getElementById('custom-tab');
            const actionTab = document.getElementById('action-tab');
            const linkFields = document.querySelectorAll('.link-field');
            const customFields = document.querySelectorAll('.custom-field');
            const actionFields = document.querySelectorAll('.action-field');
            const linkDescription = document.getElementById('link-description');
            const customDescription = document.getElementById('custom-description');
            const actionDescription = document.getElementById('action-description');
            const linkTypeInput = document.getElementById('id_link_type');
            const textField = document.querySelector('.custom-field');
            const tplBuilder = document.getElementById('template-builder');
            const tplToggle = document.getElementById('tpl-toggle');
            const tplToggleLabel = document.getElementById('tpl-toggle-label');
            const urlInput = document.getElementById('id_original_url');
            let simplemde = null;
            let builderManuallyOpen = false;

            function setTabActive(tab, color) {
                [linkTab, customTab, actionTab].forEach(function (t) {
                    t.classList.remove('text-blue-600', 'border-blue-600',
                                        'text-purple-600', 'border-purple-600',
                                        'text-green-600', 'border-green-600');
                    t.classList.add('text-gray-500', 'border-transparent');
                });
                tab.classList.remove('text-gray-500', 'border-transparent');
                tab.classList.add('text-' + color + '-600', 'border-' + color + '-600');
            }
            function showFieldSet(fields, visible) {
                fields.forEach(function (field) {
                    field.classList.toggle('hidden', !visible);
                    const label = field.querySelector('label');
                    if (label) label.classList.toggle('hidden', !visible);
                });
            }
            function syncBuilderVisibility() {
                if (!tplBuilder || !tplToggle) return;
                const url = urlInput ? urlInput.value : '';
                const hasParams = url.indexOf('{') > -1 && url.indexOf('}') > -1;
                const show = hasParams || builderManuallyOpen;
                tplBuilder.classList.toggle('hidden', !show);
                tplToggle.classList.toggle('open', show);
                if (tplToggleLabel) {
                    tplToggleLabel.textContent = show ? '{% trans "Hide template parameters" %}' : '{% trans "Add template parameters" %}';
                }
            }

            function showLinkFields() {
                setTabActive(linkTab, 'blue');
                showFieldSet(linkFields, true);
                showFieldSet(customFields, false);
                showFieldSet(actionFields, false);
                linkDescription.classList.remove('hidden');
                customDescription.classList.add('hidden');
                actionDescription.classList.add('hidden');
                linkTypeInput.value = 'LINK';
                textField.classList.add('hidden');
                if (tplToggle) tplToggle.classList.remove('hidden');
                syncBuilderVisibility();
            }

            function showCustomFields() {
                setTabActive(customTab, 'green');
                showFieldSet(linkFields, false);
                showFieldSet(customFields, true);
                showFieldSet(actionFields, false);
                customDescription.classList.remove('hidden');
                linkDescription.classList.add('hidden');
                actionDescription.classList.add('hidden');
                linkTypeInput.value = 'CUSTOM';
                textField.classList.remove('hidden');
                if (tplBuilder) tplBuilder.classList.add('hidden');
                if (tplToggle) tplToggle.classList.add('hidden');
                initializeSimpleMDE();
            }

            function showActionFields() {
                setTabActive(actionTab, 'purple');
                showFieldSet(linkFields, false);
                showFieldSet(customFields, false);
                showFieldSet(actionFields, true);
                actionDescription.classList.remove('hidden');
                linkDescription.classList.add('hidden');
                customDescription.classList.add('hidden');
                linkTypeInput.value = 'ACTION';
                textField.classList.add('hidden');
                if (tplBuilder) tplBuilder.classList.add('hidden');
                if (tplToggle) tplToggle.classList.add('hidden');
            }

            function initializeSimpleMDE() {
                if (!simplemde) {
                    var textArea = document.getElementById('id_text');
                    if (textArea) {
                        // Clear any SimpleMDE autosave cache to ensure we use the latest DB content
                        // This is important after task list updates
                        var linkId = '{{ form.instance.pk|default:"new" }}';
                        var cacheKey = 'smde_link_text_' + linkId;
                        localStorage.removeItem(cacheKey);

                        simplemde = new SimpleMDE({
                            element: textArea,
                            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"
                            ]
                        });
                    }
                }
            }

            linkTab.addEventListener('click', showLinkFields);
            customTab.addEventListener('click', showCustomFields);
            actionTab.addEventListener('click', showActionFields);

            // ── Apple-style action card: click to select ──
            document.querySelectorAll('.action-card').forEach(card => {
                card.addEventListener('click', function() {
                    const radio = this.querySelector('input[type="radio"]');
                    if (!radio) return;
                    radio.checked = true;
                    document.querySelectorAll('.action-card').forEach(c => c.classList.remove('selected'));
                    this.classList.add('selected');
                });
            });

            // ── Live preview: {query} → highlight chip ──
            const previewText = document.getElementById('msg-preview-text');
            const msgInput = document.getElementById('id_action_message_template');
            function renderPreview() {
                if (!previewText || !msgInput) return;
                const sample = '今天天气';
                const raw = msgInput.value || '@小黑 帮我看看 {query}';
                const parts = raw.split('{query}');
                let html = '';
                parts.forEach((part, i) => {
                    html += part.replace(/&/g, '&amp;').replace(/</g, '&lt;');
                    if (i < parts.length - 1) html += '<span class="qchip">' + sample + '</span>';
                });
                previewText.innerHTML = html;
            }
            if (msgInput) msgInput.addEventListener('input', renderPreview);
            renderPreview();

            /* ── Sketch-style template builder ── */
            const paramListEl = document.getElementById('tpl-param-list');
            const previewEl = document.getElementById('tpl-preview-url');
            const newNameInput = document.getElementById('tpl-new-name');
            const newDefInput = document.getElementById('tpl-new-default');
            const addParamBtn = document.getElementById('tpl-add-param');

            function parseTemplateParams(url) {
                const result = [];
                const re = /\{([^{}]*)\}/g;
                let m;
                while ((m = re.exec(url)) !== null) {
                    const inner = m[1].trim();
                    const parts = inner.split(',');
                    const name = parts[0].trim();
                    let def = null;
                    if (parts.length > 1) {
                        const dp = parts.slice(1).join(',').trim();
                        if (dp.startsWith('default=')) {
                            def = dp.slice(8).trim().replace(/^["']|["']$/g, '');
                        } else {
                            def = dp;
                        }
                    }
                    result.push({ name: name, def: def, match: m[0] });
                }
                return result;
            }
            function buildPlaceholderToken(name, def) {
                // Pure placeholder: {name} or {name,default=def}
                return '{' + name + ((def !== null && def !== '') ? ',default=' + def : '') + '}';
            }
            function buildQueryToken(name, def) {
                // Query-style full token: name={name,default=def} — matches the
                // common ?q={q} usage; pure path params can be typed manually.
                return name + '=' + buildPlaceholderToken(name, def);
            }
            function escapeHtmlTpl(s) {
                return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
            }
            function insertAtCursor(input, text) {
                const start = input.selectionStart != null ? input.selectionStart : input.value.length;
                const end = input.selectionEnd != null ? input.selectionEnd : input.value.length;
                input.value = input.value.slice(0, start) + text + input.value.slice(end);
                const pos = start + text.length;
                input.setSelectionRange(pos, pos);
                input.focus();
            }
            function appendToken(input, token) {
                const v = input.value;
                if (!v) { input.value = token; return; }
                // Cursor in the middle of the URL: insert raw (user controls position)
                if (document.activeElement === input && input.selectionStart != null &&
                    input.selectionStart === input.selectionEnd && input.selectionEnd < v.length) {
                    insertAtCursor(input, token);
                    return;
                }
                // Append at the end with a smart separator
                const hasQuery = v.indexOf('?') > -1;
                const sep = hasQuery ? '&' : '?';
                const endsSep = /[?&]$/.test(v);
                input.value = v + (endsSep ? '' : sep) + token;
                const pos = input.value.length;
                input.setSelectionRange(pos, pos);
                input.focus();
            }
            function removeTokenFromUrl(url, token) {
                // token is {name} or {name,default=...}; also drop the `name=` key
                const m = token.match(/^\{(.+?)(?:,default=.*)?\}$/);
                const name = m ? m[1] : null;
                let u = url;
                if (name) {
                    u = u.replace(new RegExp('(^|[?&])' + name + '=\\{' + name + '(?:,default=[^}]*)?\\}(?=&|$)', 'g'), '$1');
                }
                u = u.split(token).join('');
                u = u.replace(/[?&]{2,}/g, '&').replace(/^&/, '').replace(/[?&]$/, '');
                return u;
            }

            function renderTemplateBuilder() {
                if (!urlInput || !paramListEl) return;
                const url = urlInput.value || '';
                const params = parseTemplateParams(url);

                paramListEl.innerHTML = '';
                if (!params.length) {
                    const empty = document.createElement('div');
                    empty.className = 'tpl-empty';
                    empty.textContent = '{% trans "No parameters yet — click one above or type {name,default=value} in the URL." %}';
                    paramListEl.appendChild(empty);
                }
                params.forEach(function (p) {
                    const row = document.createElement('div');
                    row.className = 'tpl-param-row';

                    const nameEl = document.createElement('code');
                    nameEl.className = 'tpl-param-name';
                    nameEl.textContent = p.name;

                    const labelEl = document.createElement('span');
                    labelEl.className = 'tpl-param-label';
                    labelEl.textContent = '{% trans "default" %}';

                    const defInput = document.createElement('input');
                    defInput.className = 'tpl-param-default';
                    defInput.placeholder = '{% trans "default value" %}';
                    defInput.value = p.def || '';
                    defInput.addEventListener('input', function () {
                        const v = defInput.value.trim();
                        const token = buildPlaceholderToken(p.name, v);
                        urlInput.value = urlInput.value.split(p.match).join(token);
                        p.match = token;
                        renderTemplateBuilder();
                    });

                    const delBtn = document.createElement('button');
                    delBtn.type = 'button';
                    delBtn.className = 'tpl-param-del';
                    delBtn.textContent = '✕';
                    delBtn.title = '{% trans "Remove parameter" %}';
                    delBtn.setAttribute('aria-label', '{% trans "Remove parameter" %} ' + p.name);
                    delBtn.addEventListener('click', function () {
                        urlInput.value = removeTokenFromUrl(urlInput.value, p.match);
                        renderTemplateBuilder();
                        urlInput.dispatchEvent(new Event('input', { bubbles: true }));
                    });

                    row.appendChild(nameEl);
                    row.appendChild(labelEl);
                    row.appendChild(defInput);
                    row.appendChild(delBtn);
                    paramListEl.appendChild(row);
                });

                // grey out preset chips already in use
                document.querySelectorAll('#tpl-chips .tpl-chip').forEach(function (chip) {
                    const used = params.some(function (p) { return p.name === chip.dataset.param; });
                    chip.classList.toggle('used', used);
                });

                // live preview: fill defaults, flag missing ones
                if (previewEl) {
                    if (!url) {
                        previewEl.innerHTML = '<span class="tpl-preview-note">{% trans "Enter an original URL to see the live preview here." %}</span>';
                    } else {
                        let html = escapeHtmlTpl(url);
                        params.forEach(function (p) {
                            const escMatch = escapeHtmlTpl(p.match);
                            const valHtml = (p.def !== null && p.def !== '')
                                ? '<span class="tpl-preview-val">' + escapeHtmlTpl(p.def) + '</span>'
                                : '<span class="tpl-preview-req">' + escapeHtmlTpl(p.name) + '</span>';
                            html = html.split(escMatch).join(valHtml);
                        });
                        previewEl.innerHTML = html;
                    }
                }
            }

            // preset chips: click to insert
            document.querySelectorAll('#tpl-chips .tpl-chip').forEach(function (chip) {
                chip.addEventListener('click', function () {
                    const name = chip.dataset.param;
                    const def = chip.dataset.def || '';
                    const token = buildQueryToken(name, def);
                    appendToken(urlInput, token);
                    renderTemplateBuilder();
                    urlInput.dispatchEvent(new Event('input', { bubbles: true }));
                });
            });

            // custom param: name + default -> append
            if (addParamBtn) {
                addParamBtn.addEventListener('click', function () {
                    const name = (newNameInput.value || '').trim();
                    if (!name || !/^[A-Za-z0-9_]+$/.test(name)) {
                        newNameInput.focus();
                        newNameInput.setAttribute('style', 'border-color:#ef4444');
                        setTimeout(function () { newNameInput.removeAttribute('style'); }, 1200);
                        return;
                    }
                    const def = (newDefInput.value || '').trim();
                    const token = buildQueryToken(name, def);
                    appendToken(urlInput, token);
                    newNameInput.value = '';
                    newDefInput.value = '';
                    renderTemplateBuilder();
                    urlInput.dispatchEvent(new Event('input', { bubbles: true }));
                });
                newNameInput.addEventListener('keydown', function (e) {
                    if (e.key === 'Enter') { e.preventDefault(); addParamBtn.click(); }
                });
                newDefInput.addEventListener('keydown', function (e) {
                    if (e.key === 'Enter') { e.preventDefault(); addParamBtn.click(); }
                });
            }

            // toggle: manually show/hide the builder
            if (tplToggle) {
                tplToggle.addEventListener('click', function () {
                    builderManuallyOpen = !builderManuallyOpen;
                    syncBuilderVisibility();
                });
            }

            // sync on manual URL editing
            if (urlInput) urlInput.addEventListener('input', function () {
                renderTemplateBuilder();
                syncBuilderVisibility();
            });
            renderTemplateBuilder();
            syncBuilderVisibility();

            // Initialize form state
            if (linkTypeInput.value === 'CUSTOM') {
                showCustomFields();
            } else if (linkTypeInput.value === 'ACTION') {
                showActionFields();
            } else {
                showLinkFields();
            }

            // Check if we're creating a new link
            const isNewLink = {{ form.instance.pk|yesno:"false,true" }};
            if (isNewLink) {
                // Hide text field by default for new links
                textField.classList.add('hidden');
            }
        });
    </script>
{% endblock %}
